Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Save Bitmap as a jpeg image

Tags:

android

bitmap

In my android application i generate a qr code then save it as a jpeg image, i use this code:

imageView = (ImageView) findViewById(R.id.iv);
final Bitmap bitmap = getIntent().getParcelableExtra("pic");
imageView.setImageBitmap(bitmap);
save = (Button) findViewById(R.id.save); 
save.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {


            String path = Environment.getExternalStorageDirectory().toString();

            OutputStream fOutputStream = null;
            File file = new File(path + "/Captures/", "screen.jpg");
            if (!file.exists()) {
                file.mkdirs();
            }

            try {

                fOutputStream = new FileOutputStream(file);

                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOutputStream);

                fOutputStream.flush();
                fOutputStream.close();
                MediaStore.Images.Media.insertImage(getContentResolver(), file.getAbsolutePath(), file.getName(), file.getName());
            } catch (FileNotFoundException e) {
                e.printStackTrace();
                return;
            } catch (IOException e) {
                e.printStackTrace();
                return;
            }
        }
    });

but it always catches an exception at the line:

fOutputStream = new FileOutputStream(file);

what caused this problem???

like image 344
Mark Mamdouh Avatar asked Mar 22 '26 11:03

Mark Mamdouh


1 Answers

what caused this problem???

The statement file.mkdirs(); created a directory by the name screen.jpg. The FileOutputStream could not create a file with name screen.jpg while there is a directory by that name is found. So you got:

java.io.FileNotFoundException

Could you please replace following snippets:

File file = new File(path + "/Captures/", "screen.jpg");
if (!file.exists()) {
   file.mkdirs();
}

by the following snippets:

String dirPath = path + "/Captures/";       
File dirFile = new File(dirPath);
if(!dirFile.exists()){
   dirFile.mkdirs();
}
File file = new File(dirFile, "screen.jpg");

and see the results?

like image 119
Sanjeev Saha Avatar answered Mar 24 '26 01:03

Sanjeev Saha