【发布时间】:2015-05-21 09:43:10
【问题描述】:
我正在尝试根据宽度/高度缩放图像。这是我的方法:
private byte[] scaleImage(Bitmap image) {
byte[] image = new byte[]{};
int width= image.getWidth();
int height = image.getHeight();
int wh = width / height ;
int hw = height / width ;
int newHeight, newWidth;
if (width> 250 || height> 250) {
if (width> height) { //landscape-mode
newHeight= 250;
newWidth = Math.round((int)(long)(250 * wh));
Bitmap sizeChanged = Bitmap.createScaledBitmap(image, newWidth, newHeight, true);
int bytes = størrelseEndret.getByteCount();
ByteBuffer bb = ByteBuffer.allocate(bytes);
sizeChanged.copyPixelsFromBuffer(bb);
image = bb.array();
} else { //portrait-mode
newWidth = 250;
newHeight = Math.round((int)(long)(250 * hw));
...same
}
}
return image;
}
之后,我编写了一些代码将图像从Bitmap 转换为byte[] array,但在Debug 之后,我注意到我得到了非常奇怪的值。例如:
width = 640、height = 480,但 wh = 1、hw = 0、newHeight = 200 和 newWidth = 200?!我简直不明白为什么?我究竟做错了什么?任何帮助或提示都非常感谢。谢谢,卡尔
【问题讨论】:
-
好吧,
wh是width/height,所有的值都是整数 - 你 期望wh是什么? (如果你期待 1.3333,那么想想“整数”是什么意思……) -
你明白了。但是转换成double是明智的吗?
-
好吧,如果你想执行非整数运算,是的。或者,您可以使用
newWidth = (250 * width) / height例如 - 完全摆脱wh和hw。 -
嗯,你从哪里得到的?目前尚不清楚您是否理解这个问题......基本上我建议将
newWidth = Math.round((int)(long)(250 * wh));替换为newWidth = (250 * width) / height;以及第二个块中newHeight的等效项。 -
好的..我明白你的意思。我不确定,但也许 Ìnteger
, i will not chane todouble` 会更好?
标签: java android scale image-scaling