2017-09-22 92 views
0

我構建了一個簡單的應用程序,您可以選擇自己的照片,爲其選擇一個邊框,然後將其另存爲圖像。我這樣做的方式是在父視圖中將2個ImageView添加到彼此的頂部。然後將此父視圖轉換爲圖像並保存。但是通過這種方式,生成的圖像大小取決於設備的屏幕大小。如果設備屏幕很小,則會生成一個小的最終圖像。如何在Android中創建固定大小的圖像文件?

我想要的是無論設備如何,始終創建一個大小爲500x800像素的圖像文件。什麼是正確的方法來做到這一點?

在屏幕上的預覽可能很小,但是當我點擊保存按鈕時,我需要它正好是500x800。

回答

0

首先,將您的圖像通過爲位圖:

Bitmap bitmapImage= BitmapFactory.decodeResource(getResources(), R.drawable.large_icon); 

或者,如果你有圖像的烏里然後用這個將其轉換爲位圖:

Bitmap bitmap = BitmapFactory.decodeFile(imageUri.getPath()); 

雙方的這會給你您的圖像的位圖。

我們調整圖片大小,使用此代碼:

Bitmap scaledBitmap = Bitmap.createScaledBitmap(bitmap, imageWidth, imageHeight, true); 

然後將其轉換成文件。

0

要添加到Jason答案,我們找到了縮放圖像的最佳方法,就是用它來縮放它。

public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) { 
    int sourceWidth = source.getWidth(); 
    int sourceHeight = source.getHeight(); 
    // Compute the scaling factors to fit the new height and width, respectively. 
    // To cover the final image, the final scaling will be the bigger 
    // of these two. 
    float xScale = (float) newWidth/sourceWidth; 
    float yScale = (float) newHeight/sourceHeight; 
    float scale = Math.max(xScale, yScale); 
    // Now get the size of the source bitmap when scaled 
    float scaledWidth = scale * sourceWidth; 
    float scaledHeight = scale * sourceHeight; 
    // Let's find out the upper left coordinates if the scaled bitmap 
    // should be centered in the new size give by the parameters 
    float left = (newWidth - scaledWidth)/2; 
    float top = (newHeight - scaledHeight)/2; 
    // The target rectangle for the new, scaled version of the source bitmap will now 
    // be 
    RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight); 
    // Finally, we create a new bitmap of the specified size and draw our new, 
    // scaled bitmap onto it. 
    Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig()); 
    Canvas canvas = new Canvas(dest); 
    canvas.drawBitmap(source, null, targetRect, null); 
    return dest; 
} 
0

請嘗試下面的代碼保存位圖圖像作爲自定義高度&寬度,下面的代碼片段,讓你調整位圖

public Bitmap getResizeBitmap(Bitmap bmp, int newHeight, int newWidth) { 

int width = bmp.getWidth(); 
int height = bmp.getHeight(); 

float scaleWidth = ((float) newWidth)/width; 
float scaleHeight = ((float) newHeight)/height; 

// CREATE A MATRIX FOR THE MANIPULATION 
Matrix matrix = new Matrix(); 

// RESIZE THE BIT MAP 
matrix.postScale(scaleWidth, scaleHeight); 

// RECREATE THE NEW BITMAP 
Bitmap resizeBitmap = Bitmap.createBitmap(bmp, 0, 0, width, height, matrix, false); 

return resizeBitmap; 
} 
相關問題