我在我的資源文件夾中有30到40張圖像。而我目前使用DrawBitpMap()在我的屏幕上繪製它。但它給我一個錯誤「VM outOfMemeory錯誤」。所以我試圖調整圖像大小。現在我的圖像分辨率是160x160。現在我沒有得到那個錯誤。它運行沒有任何問題。所以我的問題是, 是否有無論如何我可以以編程方式壓縮我的圖像,而不是手動調整資源中的圖像大小?如何以編程方式壓縮圖像
任何幫助表示讚賞..
我在我的資源文件夾中有30到40張圖像。而我目前使用DrawBitpMap()在我的屏幕上繪製它。但它給我一個錯誤「VM outOfMemeory錯誤」。所以我試圖調整圖像大小。現在我的圖像分辨率是160x160。現在我沒有得到那個錯誤。它運行沒有任何問題。所以我的問題是, 是否有無論如何我可以以編程方式壓縮我的圖像,而不是手動調整資源中的圖像大小?如何以編程方式壓縮圖像
任何幫助表示讚賞..
嘗試使用這個例子
public class bitmaptest extends Activity {
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout linLayout = new LinearLayout(this);
// load the origial BitMap (500 x 500 px)
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.android);
int width = bitmapOrg.width();
int height = bitmapOrg.height();
int newWidth = 200;
int newHeight = 200;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth)/width;
float scaleHeight = ((float) newHeight)/height;
// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// rotate the Bitmap
matrix.postRotate(45);
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
width, height, matrix, true);
// make a Drawable from Bitmap to allow to set the BitMap
// to the ImageView, ImageButton or what ever
BitmapDrawable bmd = new BitmapDrawable(resizedBitmap);
ImageView imageView = new ImageView(this);
// set the Drawable on the ImageView
imageView.setImageDrawable(bmd);
// center the Image
imageView.setScaleType(ScaleType.CENTER);
// add ImageView to the Layout
linLayout.addView(imageView,
new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT
)
);
// set LinearLayout as ContentView
setContentView(linLayout);
}
}
你也可以做
Bitmap.createScaledBitmap(yourimage, 160, 160, true);
要在Android的壓縮圖像,使用方法compress
從類Bitmap
。
但我相信你想要規模,而不是壓縮。在同一個類中有一個方法來縮放它。
或者,不是每次讀取圖像時調整圖像大小,而是使用批處理文件中的ImageMagick在PC中調整大小,並將其複製到已調整大小的res /文件夾中。
這就是我解決這個問題的方法。
Bitmap originalImage= Bitmap.createScaledBitmap (BitmapFactory.decodeResource(getResources(), imageId), 160, 160, true);
正如我在我的回答中所說的,除非你有這樣一個令人信服的理由,否則我建議你在android之外縮放圖像。每次應用程序需要膨脹屏幕時,縮放每個位圖的成本太高。爲什麼每次都這樣? – Aleadam 2011-05-10 00:07:37