hpi*_*que 61 memory android bitmap sd-card
我用SD解码SD卡的位图BitmapFactory.decodeFile.有时位图大于应用程序需要或堆允许的位图,因此我BitmapFactory.Options.inSampleSize用来请求子采样(较小)位图.
问题是该平台没有强制执行inSampleSize的确切值,有时我的位图太小,或者对于可用内存而言仍然太大.
来自http://developer.android.com/reference/android/graphics/BitmapFactory.Options.html#inSampleSize:
注意:解码器将尝试满足此请求,但生成的位图可能具有与请求完全相同的不同维度.此外,2的幂通常更快/更容易让解码器兑现.
我应该如何解码SD卡中的位图以获得我需要的确切大小的位图,同时尽可能少地使用内存进行解码呢?
编辑:
当前源代码:
BitmapFactory.Options bounds = new BitmapFactory.Options();
this.bounds.inJustDecodeBounds = true;
BitmapFactory.decodeFile(filePath, bounds);
if (bounds.outWidth == -1) { // TODO: Error }
int width = bounds.outWidth;
int height = bounds.outHeight;
boolean withinBounds = width <= maxWidth && height <= maxHeight;
if (!withinBounds) {
int newWidth = calculateNewWidth(int width, int height);
float sampleSizeF = (float) width / (float) newWidth;
int sampleSize = Math.round(sampleSizeF);
BitmapFactory.Options resample = new BitmapFactory.Options();
resample.inSampleSize = sampleSize;
bitmap = BitmapFactory.decodeFile(filePath, resample);
}
Run Code Online (Sandbox Code Playgroud)
sir*_*ger 45
You are on the right track, however you are trying to do two things at once: read the file in and scale it to the appropriate size.
The first step is to read the file to a Bitmap slightly bigger than you require, using BitmapFactory.Options.inSampleSize to ensure that you do not consume excessive memory reading a large bitmap when all you want is a smaller thumbnail or screen resolution image.
The second step is to call Bitmap.createScaledBitmap() to create a new bitmap to the exact resolution you require.
Make sure you clean up after the temporary bitmap to reclaim its memory. (Either let the variable go out of scope and let the GC deal with it, or call .recycle() on it if you are loading lots of images and are running tight on memory.)
The*_*ist 15
你可能想用inJustDecodeBounds.将其设置为TRUE并按原样加载文件.
图像不会加载到内存中.但outheight和outwidth的性质BitmapFactory.Options将包含指定图像的实际尺寸PARAMS.计算你想要对它进行二次抽样的数量.即1/2或1/4或1/8等,并相应地为inSampleSize分配2/4/8等.
现在设置inJustDecodeBounds为FALSE并调用BitmapFactory.decodeFile()以加载上面计算的确切大小的图像.
首先,您需要将图像采样到最接近的采样值,以便位图变得具有内存效率,您已经完美地描述了这一点.完成后,您可以将其缩放以适合您的屏幕.
// This function taking care of sampling
backImage =decodeSampledBitmapFromResource(getResources(),R.drawable.back, width, height);
// This will scale it to your screen width and height. you need to pass screen width and height.
backImage = Bitmap.createScaledBitmap(backImage, width, height, false);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
69416 次 |
| 最近记录: |