2014-04-04 66 views
0

我需要將圖片保存到SD卡我已經做到了這一點機器人圖像的位圖壓縮無法保存圖像在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

您的位圖對象bmImg爲空 –

回答

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(); 
+0

謝謝jyomin的解決方案。它爲我工作:)但我想明白你的方法和bitmap.compress之間有什麼區別?你能解釋一下嗎? – Luqman