我正在尝试缩小位图.简而言之,图像最初来自宽度为4016的ByteArray.在使用工厂选项缩小图像后,它仍会报告宽度为4016的图像.
以下是我的代码的两个片段:
Bitmap myBitmap = null; @Override protected byte[] doInBackground(Object... params) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; if (options.outHeight > options.outWidth) { options.inSampleSize = calculateInSampleSize(options,640,960); } else { options.inSampleSize = calculateInSampleSize(options,960,640); } options.inJustDecodeBounds = false; //myImageByteArray is 4016 wide myBitmap = BitmapFactory.decodeByteArray(myImageByteArray,myImageByteArray.length,options); //This log statement outputs 4016!!! Shouldn't it be smaller since I just decoded the byteArray with options? Log.d("bitmap",myBitmap.getWidth()+""); } public int calculateInSampleSize(BitmapFactory.Options options,int reqWidth,int reqHeight) { // Raw height and width of image final int height = options.outHeight; final int width = options.outWidth; int inSampleSize = 1; if (height > reqHeight || width > reqWidth) { // Calculate ratios of height and width to requested height and // width final int heightRatio = Math.round((float) height / (float) reqHeight); final int widthRatio = Math.round((float) width / (float) reqWidth); // Choose the smallest ratio as inSampleSize value,this will // guarantee // a final image with both dimensions larger than or equal to // the // requested height and width. inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; }
更新:
以下是我的代码的两个片段:
Bitmap myBitmap = null; @Override protected byte[] doInBackground(Object... params) { final BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; //myImageByteArray is 4016 wide myBitmap = BitmapFactory.decodeByteArray(myImageByteArray,options); if (options.outHeight > options.outWidth) { options.inSampleSize = calculateInSampleSize(options,options); //This log statement outputs around 1000 now. Log.d("bitmap",this will // guarantee // a final image with both dimensions larger than or equal to // the // requested height and width. inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio; } return inSampleSize; }
解决方法
你需要两次调用.decodeByteArray(..)!一旦获得宽度和高度,.inJustDecodeBounds设置为true,然后再使用.inSampleSize获取实际缩放的Bitmap,代码中的options.outHeight和options.outWidth可能为零.
调用BitmapFactory.decodeByteArray(myImageByteArray,options);在检查出高度和宽度之前.
编辑
从Google’s Android Dev site看一下这个例子:
BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeResource(getResources(),R.id.myimage,options); int imageHeight = options.outHeight; int imageWidth = options.outWidth;