【问题标题】:Why am I getting a weird results from my scaleImage method?为什么我的 scaleImage 方法会得到奇怪的结果?
【发布时间】: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 = 640height = 480,但 wh = 1hw = 0newHeight = 200newWidth = 200?!我简直不明白为什么?我究竟做错了什么?任何帮助或提示都非常感谢。谢谢,卡尔

【问题讨论】:

  • 好吧,whwidth/height,所有的值都是整数 - 你 期望 wh 是什么? (如果你期待 1.3333,那么想想“整数”是什么意思……)
  • 你明白了。但是转换成double是明智的吗?
  • 好吧,如果你想执行非整数运算,是的。或者,您可以使用 newWidth = (250 * width) / height 例如 - 完全摆脱 whhw
  • 嗯,你从哪里得到的?目前尚不清楚您是否理解这个问题......基本上我建议将newWidth = Math.round((int)(long)(250 * wh)); 替换为newWidth = (250 * width) / height; 以及第二个块中newHeight 的等效项。
  • 好的..我明白你的意思。我不确定,但也许 Ìnteger, i will not chane to double` 会更好?

标签: java android scale image-scaling


【解决方案1】:

基本上,您遇到了整数运算问题 - 您正在执行除法以获得比例因子,但作为整数 - 所以对于 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”与“执行缩放”分开,以避免重复代码。)

【讨论】:

  • 清晰而全面。再次感谢。
猜你喜欢
  • 2020-09-21
  • 2013-05-12
  • 2018-03-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-02
  • 1970-01-01
相关资源
最近更新 更多