【问题标题】:How to reduce image size in java [duplicate]如何在java中减小图像大小[重复]
【发布时间】:2018-03-06 00:52:59
【问题描述】:

(注意:我不能使用任何直接调整图像大小的库,我想知道调整大小的核心逻辑)

我有一个尺寸为 256*256 的灰度图像。我想修改它并创建以下三个图像 a) 尺寸为 128*128 的图像 b) 尺寸为 64*64 的图像 c) 尺寸为 32*32 的图像。

伪代码

File fi = new File("E:\\input.raw");
byte[] fileContent = Files.readAllBytes(fi.toPath());

File fo= new File("E:\\output.raw");
FileOutputStream stream = new FileOutputStream(fo);

int i=0;
  for(;i<fileContent.length;i++){
  //dividing by 2 to create image with dimensions 128*128
  fileContent[i]= (byte) ((fileContent[i])/2);
    stream.write(fileContent[i]);
  }
    stream.close();

以上代码不起作用。它正在创建尺寸为 256*256 的图像。 由于某些原因,我不允许使用任何直接减小尺寸的库。我想知道如何将 256*256 图像转换为 128*128 尺寸?

【问题讨论】:

  • “由于某些原因”。你的意思是这是某种面试或家庭作业问题。虽然这里允许提出家庭作业问题,但您需要先展示您的作业。你基本上什么都没写。如果这是一个面试问题,那么你不太适合这个地方。
  • @Kayaman 我已经添加了我有问题的工作的代码 sn-p。
  • 为什么你会认为分割字节值会影响图像的大小?无论如何,这没有任何意义。
  • 只是一个旁注——如果你想从 256x256 调整到 128x128,你必须除以 4(因此你'^重新取正方形,因此需要除以 sq(2)= 4)
  • 您基本上从每个 4 像素的正方形中取出一个像素(例如左上角)。为了获得更好的效果,请先过滤原始图像以去除高频内容。

标签: java image


【解决方案1】:

使用ImageIOGraphics2D可以做到如下

BufferedImage originalImage = ImageIO.read(new File("c:\\image\\test.jpg"));
int[] dims = {128, 64, 32};

for(int dim : dims) {
    BufferedImage resizedImage = new BufferedImage(dim, dim, type);
    Graphics2D g = resizedImage.createGraphics();
    g.drawImage(originalImage, 0, 0, dim, dim, null);
    g.dispose();
    ImageIO.write(resizeImageJpg, "jpg", new File("c:\\image\\test_" + dim + "x" + dim + ".jpg"));
}

【讨论】:

  • “我不允许使用任何直接缩小尺寸的库。”
  • ImageIOGraphics2D 是 Java 内部库而不是外部库
  • 请重新阅读我的报价 - 它不是指外部库,而是直接减小尺寸的库。很明显,OP 的任务是一个相当学术的要求,只是为了表明他可以解决问题。 OP 甚至编辑了他的帖子以特别指出这一点。
  • 检查图像处理algorithms然后
【解决方案2】:

希望这会有所帮助

/**
 * scale image
 * 
 * @param sbi image to scale
 * @param imageType type of image
 * @param dWidth width of destination image
 * @param dHeight height of destination image
 * @param fWidth x-factor for transformation / scaling
 * @param fHeight y-factor for transformation / scaling
 * @return scaled image
 */
public static BufferedImage scale(BufferedImage sbi, int imageType, int dWidth, int dHeight, double fWidth, double fHeight) {
    BufferedImage dbi = null;
    if(sbi != null) {
        dbi = new BufferedImage(dWidth, dHeight, imageType);
        Graphics2D g = dbi.createGraphics();
        AffineTransform at = AffineTransform.getScaleInstance(fWidth, fHeight);
        g.drawRenderedImage(sbi, at);
    }
    return dbi;
}

【讨论】:

  • “我不允许使用任何直接缩小尺寸的库。”
  • 他/她可以随时查看库内部,看看它是如何工作的,然后自己编写
猜你喜欢
  • 2014-10-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2020-07-09
  • 2020-08-27
  • 2012-08-09
  • 2019-05-27
  • 2016-05-12
相关资源
最近更新 更多