如何在java中减小图像大小

如何在java中减小图像大小,java,image,Java,Image,(注意:我不能使用任何直接调整图像大小的库,我想知道调整大小的核心逻辑) 我有一张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"); Fi

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

我有一张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();
File fi=新文件(“E:\\input.raw”);
byte[]fileContent=Files.readAllBytes(fi.toPath());
File fo=新文件(“E:\\output.raw”);
FileOutputStream=新的FileOutputStream(fo);
int i=0;
我希望这会有所帮助

/**
 * 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;
}
使用,可按如下方式进行

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"));
}

“我不允许使用任何直接缩小尺寸的图库。”他/她可以随时检查图库内部,了解其工作原理,并“出于某些原因”自己编写。你的意思是这是一种面试或家庭作业问题。虽然这里允许有家庭作业问题,但你需要先展示你的工作。你基本上什么都没写。如果这是一个面试问题,你就不太适合这个地方。@Kayaman我已经添加了我正在讨论的工作的代码片段。你为什么认为用te值会以某种方式影响图像的大小?这根本没有任何意义。只是一个旁注-如果要将大小从256x256调整到128x128,则必须除以4(因此您需要使用正方形,因此需要除以sq(2)=4),基本上只需使用一个像素(例如左上角)为获得更好的效果,请先过滤原始图像以删除高频内容。“我不允许使用任何直接缩小尺寸的库。”java内部库不是外部库吗请重新阅读我的引文-它不是指外部库,而是指直接减少维度的库。很明显,OP的任务是一个相当学术性的请求,只是为了证明他能够解决这个问题。OP甚至编辑了他的帖子,专门指出这一点那么