acl77
acl77

Reputation: 341

android, save view image as png file

I was expecting the code below to save an image to my local sdcard but when I run the app and trigger the saveCanvasImage() method it's not doing so. When I look in the LogCat I can find a System.err entry. The text says:

java.io.FileNotFoundException: /mnt/sdcard/drawPic1.png: open failed: EACCES (permission denied)

I thought this would create a new png file and save it in the directory. I'm obviously wrong. What can I change here to make it work?

public void saveCanvasImage() {

    Log.d("bitmap","strm");
    tv.setDrawingCacheEnabled(true);
    Bitmap bm = tv.getDrawingCache();

    File fPath = Environment.getExternalStorageDirectory();
    File f = null;
    f = new File(fPath, "drawPic1.png");

    try {
    FileOutputStream strm = new FileOutputStream(f);
    bm.compress(CompressFormat.PNG, 80, strm);
    strm.close();
    }
    catch (IOException e){
        e.printStackTrace();
    }

}

Upvotes: 5

Views: 6538

Answers (5)

technical
technical

Reputation: 1

you can use this code

Bitmap bbicon;

bbicon=BitmapFactory.decodeResource(getResources(),R.drawable.bannerd10);
//ByteArrayOutputStream baosicon = new ByteArrayOutputStream();
//bbicon.compress(Bitmap.CompressFormat.PNG,0, baosicon);
//bicon=baosicon.toByteArray();

String extStorageDirectory = Environment.getExternalStorageDirectory().toString();
OutputStream outStream = null;
File file = new File(extStorageDirectory, "er.PNG");
try {
    outStream = new FileOutputStream(file);
    bbicon.compress(Bitmap.CompressFormat.PNG, 100, outStream);
    outStream.flush();
    outStream.close();
} catch(Exception e) {

}

along with permissions.

Upvotes: 0

Smile
Smile

Reputation: 375

I think you forgot to create a new file !
use this instead and set permission in manifest:

public void saveCanvasImage(Bitmap b) {

     File f = new File(Environment.getExternalStorageDirectory().toString() + "/img.png");

     f.createNewFile();  // your mistake was at here      

     try {

     FileOutputStream fos = new FileOutputStream(f);

     b.compress(CompressFormat.PNG, 100, fos);

     fos.flush();

     fos.close();

     }catch (IOException e){

         e.printStackTrace();
     }

}

and the permission :

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

Upvotes: 0

silwar
silwar

Reputation: 6518

Add following permission in your project's Manifest file permission

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

Upvotes: 0

M D
M D

Reputation: 47817

are you sure you have added this permission to write to external storage

android.permission.WRITE_EXTERNAL_STORAGE

Upvotes: 1

Hardik Joshi
Hardik Joshi

Reputation: 9507

Did you put permission ?

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

Upvotes: 7

Related Questions