Android 中 Bitmap 对象与 URI、URL、File、String、Byte、Drawable 对象的相互转换
一、URI 转 Bitmap
public static Bitmap decodeUri(Context context, Uri uri, int maxWidth, int maxHeight) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true; //只读取图片尺寸
readBitmapScale(context, uri, options);
//计算实际缩放比例
int scale = 1;
for (int i = 0; i < Integer.MAX_VALUE; i++) {
if ((options.outWidth / scale > maxWidth &&
options.outWidth / scale > maxWidth * 1.4) ||
(options.outHeight / scale > maxHeight &&
options.outHeight / scale > maxHeight * 1.4)) {
scale++;
} else {
break;
}
}
options.inSampleSize = scale;
options.inJustDecodeBounds = false;//读取图片内容
options.inPreferredConfig = Bitmap.Config.RGB_565; //根据情况进行修改
Bitmap bitmap = null;
try {
bitmap = readBitmapData(context, uri, options);
} catch (Throwable e) {
e.printStackTrace();
}
return bitmap;
}
二、URL 转 Bitmap
方法一:
Bitmap bitmap;
public Bitmap returnBitMap(final String url){
new Thread(new Runnable() {
@Override
public void run() {
URL imageurl = null;
try {
imageurl = new URL(url);
} catch (MalformedURLException e) {
e.printStackTrace();
}
try {
HttpURLConnection conn = (HttpURLConnection)imageurl.openConnection();
conn.setDoInput(true);
conn.connect();
InputStream is = conn.getInputStream();
bitmap = BitmapFactory.decodeStream(is);
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}).start();
return bitmap;
}
方法二:
public Bitmap getBitmap(String url) {
Bitmap bm = null;
try {
URL iconUrl = new URL(url);
URLConnection conn = iconUrl.openConnection();
HttpURLConnection http = (HttpURLConnection) conn;
int length = http.getContentLength();
conn.connect();
// 获得图像的字符流
InputStream is = conn.getInputStream();
BufferedInputStream bis = new BufferedInputStream(is, length);
bm = BitmapFactory.decodeStream(bis);
bis.close();
is.close();// 关闭流
}
catch (Exception e) {
e.printStackTrace();
}
return bm;
}
可配合前台线程显示
private Handler mHandler = new Handler() {
public void handleMessage(android.os.Message msg) {
switch (msg.what) {
case REFRESH_COMPLETE:
myheadimage.setImageBitmap(bitmap);//显示
break;
}
}
};
String imageUrl = "http://www.pp3.cn/uploads/201511/2015111212.jpg";
bitmap= returnBitMap(imageUrl);
mHandler.sendEmptyMessageDelayed(REFRESH_COMPLETE, 1000);
三、File 与 Bitmap
1、File 转 Bitmap
File param = new File();
Bitmap bitmap= BitmapFactory.decodeFile(param.getPath());
drawable转bitmap
Bitmap bmp = BitmapFactory.decodeResource(getResources(),R.mipmap.jcss_03 );
2、Bitmap 转 File
private String SAVE_PIC_PATH = Environment.getExternalStorageState().equalsIgnoreCase(Environment.MEDIA_MOUNTED)
? Environment.getExternalStorageDirectory().getAbsolutePath() : "/mnt/sdcard";//
private String SAVE_REAL_PATH = SAVE_PIC_PATH + "/good/savePic";//保存的确
saveFile(bmp, System.currentTimeMillis() + ".png");
//保存方法
private void saveFile(Bitmap bm, String fileName) throws IOException {
String subForder = SAVE_REAL_PATH;
File foder = new File(subForder);
if (!foder.exists()) foder.mkdirs();
File myCaptureFile = new File(subForder, fileName);
Log.e("lgq","图片保持。。。。wwww。。。。"+myCaptureFile);
ends = myCaptureFile.getPath();
if (!myCaptureFile.exists()) myCaptureFile.createNewFile();
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myCaptureFile));
bm.compress(Bitmap.CompressFormat.JPEG, 100, bos);
bos.flush();
bos.close();
ToastUtil.showSuccess(getApplicationContext(), "已保存在/good/savePic目录下", Toast.LENGTH_SHORT);
//发送广播通知系统
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(myCaptureFile);
intent.setData(uri);
this.sendBroadcast(intent);
}
if(mbitmap != null){
if(Build.VERSION.SDK_INT > Build.VERSION_CODES.Q){
saveImage29(mbitmap);
}else{
if ( saveImage(file, mbitmap)){
LgqLogPlus.e("路径---3-- "+file);
//发送广播通知系统
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(new File(file));
intent.setData(uri);
this.sendBroadcast(intent);
}
}
}
/**
* API29 中的最新保存图片到相册的方法
*/
private void saveImage29(Bitmap toBitmap) {
//开始一个新的进程执行保存图片的操作
Uri insertUri = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, new ContentValues());
//使用use可以自动关闭流
try {
OutputStream outputStream = getContentResolver().openOutputStream(insertUri, "rw");
if (toBitmap.compress(Bitmap.CompressFormat.JPEG, 90, outputStream)) {
Log.e("保存成功", "success");
} else {
Log.e("保存失败", "fail");
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
//统一方法将图片Bitmap保存在文件中
public static boolean saveImageToFile(Context mContext,String fileName, Bitmap frame) {
if (fileName == null || fileName.length() <= 0)
return false;
if (frame == null || frame.getByteCount() <= 0)
return false;
ByteArrayOutputStream baos = new ByteArrayOutputStream();
frame.compress(Bitmap.CompressFormat.JPEG, 100, baos);//质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中
int options = 100;
while (baos.toByteArray().length / 1024 > 100) { //循环判断如果压缩后图片是否大于100kb,大于继续压缩
baos.reset();//重置baos即清空baos
//第一个参数 :图片格式 ,第二个参数: 图片质量,100为最高,0为最差 ,第三个参数:保存压缩后的数据的流
frame.compress(Bitmap.CompressFormat.JPEG, options, baos);//这里压缩options%,把压缩后的数据存放到baos中
options -= 10;//每次都减少10
}
ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray());//把压缩后的数据baos存放到ByteArrayInputStream中
Bitmap bitmap = BitmapFactory.decodeStream(isBm, null, null);//把ByteArrayInputStream数据生成图片
if(bitmap!=null){
AppLog.Loge("压缩后图片大小为:"+bitmap.getByteCount() + "---路径:"+fileName);
saveBitmap(bitmap,fileName);
}
return true;
}
public static void saveBitmap(Bitmap bitmap,String path) {
new Thread(new Runnable() {
@Override
public void run() {
String savePath;
File filePic;
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
savePath = path;
} else {
AppLog.Loge( "saveBitmap failure : sdcard not mounted");
return;
}
try {
filePic = new File(savePath);
if (!filePic.exists()) {
filePic.getParentFile().mkdirs();
filePic.createNewFile();
}
FileOutputStream fos = new FileOutputStream(filePic);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fos);
fos.flush();
fos.close();
} catch (IOException e) {
AppLog.Loge( "保存图片失败 saveBitmap: " + e.getMessage());
return;
}
AppLog.Loge( "saveBitmap success: " + filePic.getAbsolutePath());
}
}).start();
}
四、Bitmap 与 String
Bitmap frame = BitmapFactory.decodeResource(getResources(),R.mipmap.iv_charge2 );
byte[] snapshot = getByteArrayFromBitmap(frame);
if (snapshot!=null){
String imageString = new String(Base64.encode(snapshot,Base64.DEFAULT));
if (imageString!=null){
byte[] bytsSnapshot = Base64.decode(imageString.getBytes(), Base64.DEFAULT);
Bitmap snapshot2 = (bytsSnapshot != null && bytsSnapshot.length > 0) ? getBitmapFromByteArray(bytsSnapshot) : null;
imageView.setImageBitmap(snapshot2);
}
}
工具:
public static byte[] getByteArrayFromBitmap(Bitmap bitmap) {
if (bitmap != null && !bitmap.isRecycled()) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
return bos.toByteArray();
} else {
return null;
}
}
public static Bitmap getBitmapFromByteArray(byte[] byts) {
InputStream is = new ByteArrayInputStream(byts);
return BitmapFactory.decodeStream(is, null, getBitmapOptions(2));
}
public static BitmapFactory.Options getBitmapOptions(int scale) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true;
options.inInputShareable = true;
options.inSampleSize = scale;
try {
BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean(options, true);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return options;
}
private static void readBitmapScale(Context context, Uri uri, BitmapFactory.Options options) {
if (uri == null) {
return;
}
String scheme = uri.getScheme();
if (ContentResolver.SCHEME_CONTENT.equals(scheme) ||
ContentResolver.SCHEME_FILE.equals(scheme)) {
InputStream stream = null;
try {
stream = context.getContentResolver().openInputStream(uri);
BitmapFactory.decodeStream(stream, null, options);
} catch (Exception e) {
Log.w("readBitmapScale", "Unable to open content: " + uri, e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
Log.e("readBitmapScale", "Unable to close content: " + uri, e);
}
}
}
} else if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {
Log.e("readBitmapScale", "Unable to close content: " + uri);
} else {
Log.e("readBitmapScale", "Unable to close content: " + uri);
}
}
private static Bitmap readBitmapData(Context context, Uri uri, BitmapFactory.Options options) {
if (uri == null) {
return null;
}
Bitmap bitmap = null;
String scheme = uri.getScheme();
if (ContentResolver.SCHEME_CONTENT.equals(scheme) ||
ContentResolver.SCHEME_FILE.equals(scheme)) {
InputStream stream = null;
try {
stream = context.getContentResolver().openInputStream(uri);
bitmap = BitmapFactory.decodeStream(stream, null, options);
} catch (Exception e) {
Log.e("readBitmapData", "Unable to open content: " + uri, e);
} finally {
if (stream != null) {
try {
stream.close();
} catch (IOException e) {
Log.e("readBitmapData", "Unable to close content: " + uri, e);
}
}
}
} else if (ContentResolver.SCHEME_ANDROID_RESOURCE.equals(scheme)) {
Log.e("readBitmapData", "Unable to close content: " + uri);
} else {
Log.e("readBitmapData", "Unable to close content: " + uri);
}
return bitmap;
}
五、byte[] 与 Bitmap
方法一
1、Bitmap 转 byte[]
private byte[] Bitmap2Bytes(Bitmap bm) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, baos);
return baos.toByteArray();
}
2、byte[] 转 Bitmap
private Bitmap Bytes2Bimap(byte[] b) {
if (b.length != 0) {
return BitmapFactory.decodeByteArray(b, 0, b.length);
} else {
return null;
}
}
方法二
1、Bitmap 转 byte[]
Bitmap frame = mCamera != null ? mCamera.Snapshot(mSelectedChannel) : null;
frame = rotate(frame, 90);
byte[] snapshot = getByteArrayFromBitmap(frame);
if (snapshot!=null){
tring imageString = new String(Base64.encode(snapshot,Base64.DEFAULT));
LgqLogPlus.e("获取到imgstring保存了===== "+imageString);
SharedPreUtil.putString(mDevUID,imageString);
}
public static byte[] getByteArrayFromBitmap(Bitmap bitmap) {
if (bitmap != null && !bitmap.isRecycled()) {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0, bos);
return bos.toByteArray();
} else {
return null;
}
}
2、byte[] 转 Bitmap
String imgstring = SharedPreUtil.getString(this,mDevUID);
LgqLogPlus.e("获取到imgstring==== "+imgstring);
if (imgstring!=null){
byte[] bytsSnapshot = Base64.decode(imgstring.getBytes(), Base64.DEFAULT);
Bitmap snapshot = (bytsSnapshot != null && bytsSnapshot.length > 0) ? getBitmapFromByteArray(bytsSnapshot) : null;
bgimg.setImageBitmap(snapshot);
}
public static Bitmap getBitmapFromByteArray(byte[] byts) {
InputStream is = new ByteArrayInputStream(byts);
return BitmapFactory.decodeStream(is, null, getBitmapOptions(2));
}
public static BitmapFactory.Options getBitmapOptions(int scale) {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPurgeable = true;
options.inInputShareable = true;
options.inSampleSize = scale;
try {
BitmapFactory.Options.class.getField("inNativeAlloc").setBoolean(options, true);
} catch (IllegalArgumentException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (SecurityException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IllegalAccessException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (NoSuchFieldException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return options;
}