【问题标题】:How to save a bitmap on internal storage如何在内部存储中保存位图
【发布时间】:2013-03-17 17:38:44
【问题描述】:

这是我的代码,我想将此位图保存在我的内部存储中。公共布尔值 saveImageToInternalStorage 是来自谷歌的代码,但我不知道如何使用它。当我触摸 button2 时,跟随 button1 的动作。

public class MainActivity extends Activity implements OnClickListener {
Button btn, btn1;
SurfaceView sv;
Bitmap bitmap;
Canvas canvas;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn=(Button)findViewById(R.id.button1);
    btn1=(Button)findViewById(R.id.button2);
    sv=(SurfaceView)findViewById(R.id.surfaceView1);

    btn.setOnClickListener(this);
    btn1.setOnClickListener(this);

    bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);

}
@Override
public void onClick(View v) {
    canvas=sv.getHolder().lockCanvas();
    if(canvas==null) return;
    canvas.drawBitmap(bitmap, 100, 100, null);
    sv.getHolder().unlockCanvasAndPost(canvas);


}

public boolean saveImageToInternalStorage(Bitmap image) {

    try {
    // Use the compress method on the Bitmap object to write image to
    // the OutputStream
    FileOutputStream fos = openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);

    // Writing the bitmap to the output stream
    image.compress(Bitmap.CompressFormat.PNG, 100, fos);
    fos.close();

    return true;
    } catch (Exception e) {
    Log.e("saveToInternalStorage()", e.getMessage());
    return false;
    }
    }
 }

【问题讨论】:

    标签: android bitmap save


    【解决方案1】:

    要将您的位图保存在 sdcard 中,请使用以下代码

    商店图片

    private void storeImage(Bitmap image) {
        File pictureFile = getOutputMediaFile();
        if (pictureFile == null) {
            Log.d(TAG,
                    "Error creating media file, check storage permissions: ");// e.getMessage());
            return;
        } 
        try {
            FileOutputStream fos = new FileOutputStream(pictureFile);
            image.compress(Bitmap.CompressFormat.PNG, 90, fos);
            fos.close();
        } catch (FileNotFoundException e) {
            Log.d(TAG, "File not found: " + e.getMessage());
        } catch (IOException e) {
            Log.d(TAG, "Error accessing file: " + e.getMessage());
        }  
    }
    

    获取图片存储路径

    /** Create a File for saving an image or video */
    private  File getOutputMediaFile(){
        // To be safe, you should check that the SDCard is mounted
        // using Environment.getExternalStorageState() before doing this. 
        File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
                + "/Android/data/"
                + getApplicationContext().getPackageName()
                + "/Files"); 
    
        // This location works best if you want the created images to be shared
        // between applications and persist after your app has been uninstalled.
    
        // Create the storage directory if it does not exist
        if (! mediaStorageDir.exists()){
            if (! mediaStorageDir.mkdirs()){
                return null;
            }
        } 
        // Create a media file name
        String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
        File mediaFile;
            String mImageName="MI_"+ timeStamp +".jpg";
            mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);  
        return mediaFile;
    } 
    

    编辑 我在您的 cmets 中编辑了 onclick 视图,button1 和 button2 函数将分别执行。

    public onClick(View v){
    
    switch(v.getId()){
    case R.id.button1:
    //Your button 1 function
    break;
    case R.id. button2:
    //Your button 2 function
    break;
    } 
    }
    

    【讨论】:

    • capturedImage 和 mImageName 必须如何创建?
    • 非常感谢,但是button2仍然遵循button1的功能
    • 我喜欢使用 JPEG:Bitmap.CompressFormat.JPEG
    • 我不知道为什么这是公认的答案,因为问题是关于内部存储的,而这个答案是关于外部存储的......
    • 问题是关于内部存储 :(
    【解决方案2】:
    private static void SaveImage(Bitmap finalBitmap) {
    
        String root = Environment.getExternalStorageDirectory().getAbsolutePath();
        File myDir = new File(root + "/saved_images");
        myDir.mkdirs();
    
        String fname = "Image-"+ o +".jpg";
        File file = new File (myDir, fname);
        if (file.exists ()) file.delete ();
        try {
            FileOutputStream out = new FileOutputStream(file);
            finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
            out.flush();
            out.close();
    
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    

    【讨论】:

      【解决方案3】:

      修改onClick()如下:

      @Override
      public void onClick(View v) {
          if(v == btn) {
              canvas=sv.getHolder().lockCanvas();
              if(canvas!=null) {
                  canvas.drawBitmap(bitmap, 100, 100, null);
                  sv.getHolder().unlockCanvasAndPost(canvas);
              }
          } else if(v == btn1) {
              saveBitmapToInternalStorage(bitmap);
          }
      }
      

      有几种方法可以强制在btn1 之前按下btn,以便在您尝试保存之前绘制bitmap

      我建议您最初禁用btn1,然后在单击btn 时启用它,如下所示:

      if(v == btn) {
          ...
          btn1.setEnabled(true);
      }
      

      【讨论】:

      • 如何从 if(view == btn) 和 else if(view == btn1) 查看?
      • 我编辑了“视图”->“v”。这两个if() 语句确定在您的onClick() 函数中按下了哪个按钮。
      【解决方案4】:

      将文件保存到目录中

        public static Uri saveImageToInternalStorage(Context mContext, Bitmap bitmap){
      
          String mTimeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
      
          String mImageName = "snap_"+mTimeStamp+".jpg";
      
          ContextWrapper wrapper = new ContextWrapper(mContext);
      
          File file = wrapper.getDir("Images",MODE_PRIVATE);
      
          file = new File(file, "snap_"+ mImageName+".jpg");
      
          try{
      
              OutputStream stream = null;
      
              stream = new FileOutputStream(file);
      
              bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
      
              stream.flush();
      
              stream.close();
      
          }catch (IOException e) 
          {
              e.printStackTrace();
          }
      
          Uri mImageUri = Uri.parse(file.getAbsolutePath());
      
          return mImageUri;
      }
      

      需要的权限

      <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
      

      【讨论】:

        【解决方案5】:

        您也许可以使用以下方法来解码、压缩和保存图像:

             @Override
             public void onClick(View view) {
                        onItemSelected1();
                        InputStream image_stream = null;
                        try {
                            image_stream = getContentResolver().openInputStream(myUri);
                        } catch (FileNotFoundException e) {
                            e.printStackTrace();
                        }
        
                        Bitmap image= BitmapFactory.decodeStream(image_stream );
                        // path to sd card
                        File path=Environment.getExternalStorageDirectory();
                        //create a file
                        File  dir=new File(path+"/ComDec/");
                        dir.mkdirs();
                        Date date=new Date();
                        File file=new File(dir,date+".jpg");
        
                        OutputStream out=null;
                        try{
                            out=new FileOutputStream(file);
                            image.compress(format,size,out);
                            out.flush();
                            out.close();
        
        
                            MediaStore.Images.Media.insertImage(getContentResolver(), image," yourTitle "," yourDescription");
        
                            image=null;
        
        
                        }
                        catch (IOException e)
                        {
                            e.printStackTrace();
                        }
                        Toast.makeText(SecondActivity.this,"Image Save Successfully",Toast.LENGTH_LONG).show();
                    }
                });
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-06-14
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多