1. 使用Bundle和intent。(传递图片有大小限制,否则会导致OOM)(个人推荐用这种,限制传递图片大小)
(1). 使用Bundle的putParcelable方法:
Bundle bundle = new Bundle(); Intent intent = new Intent(); intent.putExtra("bitmap", bitmap); bundle.putParcelable("bitmap", bitmap);
传递图片较小(亲测,可传递小于88K的图片)
(2).使用Bundle的putByteArray,先压缩图片:
ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.JPEG, 85, baos); byte[] bitmapByte = baos.toByteArray();这个也有限制:最大可分享bitmapByte.length <= 517654, 大于等于523523的图片传递不成功,区间值中其它的没有进一步实测~Bundle bundle = new Bundle();bundle.putByteArray("bitmapByte", bitmapByte);//取图片的时候byte[] bitmapByte = bundle.getByteArray("bitmapByte");
可参考:quality为85(压缩比25%)时:可分享的最大图片是1.2多一点
压缩比越大,可传递图片越大,且不会失像素~
2. 存到sdcard,再读取。(IO存取过程消耗较大)
(1).图片存到sdcard:
if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) { picPath = Environment.getExternalStorageDirectory() + File.separator + getBaseContext().getPackageName() + File.separator + "sharePics"; String timestamp = String.valueOf(new Date().getTime()); picName = "flight_" + timestamp; writeToSDCard(picPath, picName, bytes); }
public static void writeToSDCard(String path, String filename, byte[] fileContent) { FileOutputStream outputStream = null; createDir(path); File file = new File(path, filename); try { outputStream = new FileOutputStream(file); outputStream.write(fileContent); } catch (IOException e) { QLog.e("writeToSDCard", e); } finally { if (outputStream != null) { try { outputStream.close(); } catch (IOException e) { QLog.e("writeToSDCard", e); } } } } public static void createDir(String path) { File file = new File(path); if (!file.exists()) { file.mkdirs(); } }
(2).读取图片:
String picPath = bundle.getString("picPath"); String picName = bundle.getString("picName");byte[] picByte = toByteArray(picPath, picName);Bitmap bitmapFromFile = bytes2Bimap(picByte);
public static byte[] toByteArray(String path, String filename) { File f = new File(path, filename); if (!f.exists()) { } ByteArrayOutputStream bos = new ByteArrayOutputStream((int) f.length()); BufferedInputStream in = null; try { in = new BufferedInputStream(new FileInputStream(f)); int buf_size = 1024; byte[] buffer = new byte[buf_size]; int len = 0; while (-1 != (len = in.read(buffer, 0, buf_size))) { bos.write(buffer, 0, len); } return bos.toByteArray(); } catch (IOException e) { e.printStackTrace(); } finally { try { in.close(); bos.close(); } catch (IOException e) { e.printStackTrace(); } } return null; }
public Bitmap bytes2Bimap(byte[] b) { if (b.length != 0) { return BitmapFactory.decodeByteArray(b, 0, b.length); } else { return null; } }