您的位置:首页 > 移动开发 > Android开发

Activity之间传递Bitmap方式

2017-01-17 17:20 295 查看
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();
Bundle bundle = new Bundle();
bundle.putByteArray("bitmapByte", bitmapByte);
//取图片的时候
byte[] bitmapByte = bundle.getByteArray("bitmapByte");

这个也有限制:最大可分享bitmapByte.length <= 517654, 大于等于523523的图片传递不成功,区间值中其它的没有进一步实测~

可参考: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;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息