繁体   English   中英

为什么我的scaleImage方法会得到奇怪的结果?

[英]Why am I getting a weird results from my scaleImage method?

我正在尝试根据宽度/高度缩放图像。 这是我的方法:

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 = 640height = 480 ,但wh = 1hw = 0newHeight = 200newWidth = 200? 我根本不明白为什么? 我究竟做错了什么? 任何帮助或提示,我们将不胜感激。 谢谢卡尔

基本上,您遇到整数运算的问题-正在执行除法以获得比例因子,但作为整数-对于640x480之类的东西,比例因子将为1和0,因为640/480为1,而480/640为0。

您可以将其更改为(x1*y2)/y1 ,而不是将其作为(x1/y1)*y2 ,以便随后执行除法。 只要您在乘法中不溢出整数极限(在这里不太可能)就可以了。 因此,我将您的代码重写为:

private byte[] scaleImage(Bitmap image) {
  byte[] image = new byte[]{};
  int width = image.getWidth();
  int height = image.getHeight();
  int newHeight, newWidth;
  if (width > 250 || height > 250) {
    if (width > height) { //landscape-mode
      newHeight = 250;
      newWidth = (newHeight * width) / height;
    } else {
      newWidth = 250;
      newHeight = (newWidth * height) / width;
    }
  } else {
    // Whatever you want to do here
  }
  // Now use newWidth and newHeight
}

(如果可能,我肯定会将“计算newWidthnewHeight ”与“执行缩放”分开,以避免重复代码。)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM