在安卓开发中,会经常用到将图片转化成byte[]数组保存或者传输,然后再将byte[]数组转换成图片格式,得到图片。
一、将图片转换成byte[]数组
public static byte[] bitmap2Bytes(Bitmap bitmap){
if( null != bitmap ){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); //注意压缩png和jpg的格式和质量
return baos.toByteArray();
}
return null;
}
二、将byte[]数组转换成bitmap
public static Bitmap bytes2Bitmap(byte[] bytes, BitmapFactory.Options opts){
if ( null != opts ){
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,opts);
}else{
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
}
}
三、将byte[]数组转换成图片文件并保存起来
private void bytes2ImageFile(byte[] bytes) {
try {
//将文件保存在路径“/storage/emulated/0/demo.jpg”
File file = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/demo.jpg");
FileOutputStream fos = new FileOutputStream(file);
fos.write(bytes, 0, bytes.length);
fos.flush();
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}
四、将bitmap转换成drawable
public Drawable bitmap2Drawable(Bitmap bitmap){
new BitmapDrawable(getResources(), bitmap)
}
关于静态方法使用getResources()报错的问题:Non-static method ‘getResources()’ cannot be referenced from a static context
解决:
private static Context mContext = null;
mContext = getActivity();
public Drawable bitmap2Drawable(Bitmap bitmap){
new BitmapDrawable(mContext.getResources(), bitmap)
}
五、将drawable转换成bitmap
public Bitmap drawable2bitmap(Drawable drawable){
new ((BitmapDrawable) drawable).getBitmap();
}
在安卓开发里,常需将图片转化为byte[]数组进行保存或传输,再将byte[]数组转回图片格式。博客介绍了图片与byte[]数组、Bitmap和Drawable之间的相互转换,还提及将byte[]数组转换成图片文件保存,以及解决静态方法使用getResources()报错的问题。
1515

被折叠的 条评论
为什么被折叠?



