Android之Bitmap对象和字节流之间的相互转换

将图片内容解析成字节数组,将字节数组转换为ImageView可调用的Bitmap对象,图片缩放,把字节数组保存为一个文件,把Bitmap转Byte
import java.io.BufferedOutputStream;    
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Matrix;

public class ImageDispose {



/**
* @param 将图片内容解析成字节数组
* @param inStream
* @return byte[]
* @throws Exception
*/
public static byte[] readStream(InputStream inStream) throws Exception {
byte[] buffer = new byte[1024];
int len = -1;
ByteArrayOutputStream outStream = new ByteArrayOutputStream();
while ((len = inStream.read(buffer)) != -1) {
outStream.write(buffer, 0, len);
}
byte[] data = outStream.toByteArray();
outStream.close();
inStream.close();
return data;

}
/**
* @param 将字节数组转换为ImageView可调用的Bitmap对象
* @param bytes
* @param opts
* @return Bitmap
*/
public static Bitmap getPicFromBytes(byte[] bytes,
BitmapFactory.Options opts) {
if (bytes != null)
if (opts != null)
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length,
opts);
else
return BitmapFactory.decodeByteArray(bytes, 0, bytes.length);
return null;
}
/**
* @param 图片缩放
* @param bitmap 对象
* @param w 要缩放的宽度
* @param h 要缩放的高度
* @return newBmp 新 Bitmap对象
*/
public static Bitmap zoomBitmap(Bitmap bitmap, int w, int h){
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidth = ((float) w / width);
float scaleHeight = ((float) h / height);
matrix.postScale(scaleWidth, scaleHeight);
Bitmap newBmp = Bitmap.createBitmap(bitmap, 0, 0, width, height,
matrix, true);
return newBmp;
}

/**
* 把Bitmap转Byte
*/
public static byte[] Bitmap2Bytes(Bitmap bm){
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
/**
* 把字节数组保存为一个文件
*/
public static File getFileFromBytes(byte[] b, String outputFile) {
BufferedOutputStream stream = null;
File file = null;
try {
file = new File(outputFile);
FileOutputStream fstream = new FileOutputStream(file);
stream = new BufferedOutputStream(fstream);
stream.write(b);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
}
}
return file;
}

}


见博客文章:http://blog.csdn.net/itheima6/article/details/7516631
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值