问题
I have an application where the user can draw to a view whose dimensions are W = Match Parent and H = 250dp.
I need to resize it to W = 399pixels and H = 266pixels so I can print it properly via a bluetooth thermal printer. I am getting the desired dimensions of the resized image, however, the output I get is a chopped version of the original whose dimensions are the scaled dimensions I want.
This is the code I use to get the data from the view and resize it.
Bitmap bitmap = Bitmap.createBitmap(mView.getWidth(), mView.getHeight(), Bitmap.Config.ARGB_8888);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
//Resize the image
Bitmap resizedImage = Bitmap.createScaledBitmap(bitmap, 399, 266, false);
//code for resized
Canvas c = new Canvas(resizedImage);
c.drawColor(Color.WHITE);
c.drawBitmap(resizedImage, 0, 0, null);
mView.draw(c);
resizedImage.compress(Bitmap.CompressFormat.PNG, 90, stream);
What am I doing wrong here?
EDIT: I think the problem is that the canvas I'm drawing the resized image to is large, and for some reason, the draw command does not work and whenever I print, it's printing the original contents of that canvas.
回答1:
Try to use Matrix
to resize bitmap.
public static Bitmap resizeBitmap(Bitmap bitmap, int width, int height) {
int w = bitmap.getWidth();
int h = bitmap.getHeight();
Matrix matrix = new Matrix();
float scaleWidth = ((float) width / w);
float scaleHeight = ((float) height / h);
matrix.postScale(scaleWidth, scaleHeight);
Bitmap newbmp = Bitmap.createBitmap(bitmap, 0, 0, w, h, matrix, true);
return newbmp;
}
回答2:
public static Bitmap resizeBitmap(Bitmap bitmap, int width, int height) { //width - height in pixel not in DP
bitmap.setDensity(Bitmap.DENSITY_NONE);
Bitmap newbmp = Bitmap.createScaledBitmap(bitmap, width, height, true);
return newbmp;
}
回答3:
The problem is that the Bitmap of the resized image is instantiated right after the creation of the bitmap that gets the user input. This was my code that worked.
However, note that I made an imageView to hold the resized image.
ByteArrayOutputStream stream = new ByteArrayOutputStream();
//get the user input and store in a bitmap
Bitmap bitmap = Bitmap.createBitmap(mView.getWidth(), mView.getHeight(), Bitmap.Config.ARGB_8888);
//Create a canvas containing white background and draw the user input on it
//this is necessary because the png format thinks that white is transparent
Canvas c = new Canvas(bitmap);
c.drawColor(Color.WHITE);
c.drawBitmap(bitmap, 0, 0, null);
//redraw
mView.draw(c);
//create resized image and display
Bitmap resizedImage = Bitmap.createScaledBitmap(bitmap, 399, 266, true);
imageView.setImageBitmap(resizedImage);
来源:https://stackoverflow.com/questions/18393474/android-resizing-bitmap-cuts-it-instead-of-scaling-it