android图像位图压缩无法在SD卡中保存图像

时间:2014-04-04 11:01:07

标签: android image save sd-card

我需要将图像保存到sd卡我已经完成了这个

Bitmap bmImg = imageCacher
                    .getBitmap("http://leewayinfotech.com//mobile//ebook//uploaded_images//abstract//165//16521396377593_4.jpg");
String str = data[currentItem];

Bitmap bmImg = imageCacher.getBitmap(str);

try {
        String path1 = android.os.Environment.getExternalStorageDirectory().toString();
        Log.i("in save()", "after mkdir");
        File file=new File(path1 + "/"+appName);
        if (!file.exists())
        file.mkdirs();
        filename = new File(file.getAbsolutePath()+"/"+imageName+".jpeg");
        Log.i("in save()", "after file");
        FileOutputStream out = new FileOutputStream(filename);
        Log.i("in save()", "after outputstream");
        bmImg.compress(Bitmap.CompressFormat.JPEG, 90, out);
        out.flush();
} catch(Exception e) {

}

但我的logcat说:

04-04 16:23:32.301: I/in save()(14452): after outputstream
04-04 16:23:32.301: W/System.err(14452): java.lang.NullPointerException
04-04 16:23:32.301: W/System.err(14452):    at com.leeway.hdwallpaper.My_Pagging_Activity$Image_Pager_Adpter$1.onLongClick(My_Pagging_Activity.java:219)
04-04 16:23:32.301: W/System.err(14452):    at android.view.View.performLongClick(View.java:4207)
04-04 16:23:32.301: W/System.err(14452):    at android.view.View$CheckForLongPress.run(View.java:17174)
04-04 16:23:32.301: W/System.err(14452):    at android.os.Handler.handleCallback(Handler.java:643)
04-04 16:23:32.301: W/System.err(14452):    at android.os.Handler.dispatchMessage(Handler.java:92)
04-04 16:23:32.301: W/System.err(14452):    at android.os.Looper.loop(Looper.java:137)
04-04 16:23:32.301: W/System.err(14452):    at android.app.ActivityThread.main(ActivityThread.java:4803)
04-04 16:23:32.301: W/System.err(14452):    at java.lang.reflect.Method.invokeNative(Native Method)
04-04 16:23:32.301: W/System.err(14452):    at java.lang.reflect.Method.invoke(Method.java:511)
04-04 16:23:32.301: W/System.err(14452):    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
04-04 16:23:32.301: W/System.err(14452):    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
04-04 16:23:32.301: W/System.err(14452):    at dalvik.system.NativeStart.main(Native Method)
                                out.close();
                                Log.i("in save()", "after outputstream closed");

中给出错误

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

1 个答案:

答案 0 :(得分:2)

试试这个:

File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath(),     "AppName");
        if (!file.exists()) {
            file.mkdirs();
                        }
String image_name = "IMG_Name.jpg";
File outputFile = new File(file, image_name);
FileOutputStream fos = new FileOutputStream(outputFile);
        fos.flush();
        fos.write(bytes.toByteArray());
       fos.close();