Save bitmap to file

[亡魂溺海] 提交于 2019-12-11 08:28:03

问题


I have tried to implement undo and redo feature in android fingerpaint app. I have tried to implement using the below code.

Error

03-26 20:42:12.020: W/System.err(28056): java.lang.NullPointerException
03-26 20:42:12.020: W/System.err(28056):    at baked.soft.FirstActivity.toJPEGFile(FirstActivity.java:341)
03-26 20:42:12.020: W/System.err(28056):    at baked.soft.FirstActivity.onOptionsItemSelected(FirstActivity.java:314)

FirstActivity

public boolean onOptionsItemSelected(MenuItem item){
     switch (item.getItemId()) {
     case R.id.tools:
        ll.setVisibility(LinearLayout.VISIBLE);
        return true;
     case R.id.import_pics:
         getPhotos();
         return true;
     case R.id.save:
        toJPEGFile();
     return true;
     case R.id.trash:
         trash();

         return true;
     }
    return false;

}

private void toJPEGFile() {
    // TODO Auto-generated method stub
    String root = Environment.getExternalStorageDirectory().toString();
    File myDir = new File(root + "/saved_images");    
    myDir.mkdirs();
    Random generator = new Random();
    int n = 10000;
    n = generator.nextInt(n);
    String fname = "Image-"+ n +".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); // ERROR 341 LINE
           out.flush();
           out.close();

    } catch (Exception e) {
           e.printStackTrace();
    }
}

I don't know where is wrong. please help me. Thanks in advance!


回答1:


       finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);

as you point out is the error line.

finalBitmap has not been initialised.

Aka, it is not a bitmap, it is a null value. Make sure you load your bitmap into this variable first.

finalBitmap = .... // assign finalBitmap.
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);  // Then save to file

Edit:

reading from your comment, one way to do it would be to do the following, in onDraw method:

  canvas.drawBitmap(bitmap, 0, 0, paint);
  finalBitmap = bitmap;

But again, ive no idea where you are getting bitmap from. Is this another global variable? Maybe you could just change finalBitmap.compress... to bitmap.compress...



来源:https://stackoverflow.com/questions/15645048/save-bitmap-to-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!