Byte[] Bitmap 转化

public Bitmap getBitmap(byte[] bytes) { Options opt = new Options(); opt.inJustDecodeBounds = true; //只分配边界不分配像素DecodeBitmap时候 decodeBitmap(bytes, opt); if (opt.outHeight * opt.outWidth < MAX_IMAGE_PIXELS) { return decodeBitmap(bytes, null); } return null; } public byte[] getBytes(Bitmap bitmap) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bitmap.compress(Bitmap.CompressFormat.PNG, 100, baos); return baos.toByteArray(); } public Bitmap resizeImage(byte[] original, int maxWidth, int maxHeight, boolean stretch) { Options opt = new Options(); opt.inJustDecodeBounds = true; decodeBitmap(original, opt); int width = opt.outWidth; int height = opt.outHeight; // Scale the bitmap as we're decoding it to avoid out of memory errors. opt.inJustDecodeBounds = false; if (width > maxWidth && height > maxHeight) { opt.inSampleSize = Math.min(width / maxWidth, height / maxHeight); } else if (width > maxWidth) { opt.inSampleSize = width / maxWidth; } else if (height > maxHeight) { opt.inSampleSize = height / maxHeight; } int powerOfTwo = 1; while (powerOfTwo * 2 < opt.inSampleSize) { powerOfTwo *= 2; } // According to docs, powers of two are more efficient and more accurate. opt.inSampleSize = powerOfTwo; Bitmap scaled = decodeBitmap(original, opt); if (scaled != null) { width = scaled.getWidth(); height = scaled.getHeight(); float scaleWidth = ((float)maxWidth) / width; float scaleHeight = ((float)maxHeight) / height; if (!stretch) { if ((scaleWidth * height) > maxHeight) { scaleWidth = scaleHeight; } else { scaleHeight = scaleWidth; } } Matrix matrix = new Matrix(); matrix.postScale(scaleWidth, scaleHeight); return Bitmap.createBitmap(scaled, 0, 0, width, height, matrix, true); //缩放图像 } return null; } private Bitmap decodeBitmap(byte[] bytes, Options opt) { Bitmap retval = null; if (bytes != null) { try { retval = BitmapFactory.decodeByteArray(bytes, 0, bytes.length, opt); } catch (OutOfMemoryError oome) { Log.e(ImageHelper.class.getName(), "Out of memory, trying GC...", oome); System.gc(); } catch (Exception e) { Log.e(ImageHelper.class.getName(), "Error decoding bitmap",e); } } return retval; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值