Python中文网

一个关于 编程问题的解答网站.

有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

java裁剪图像并将其合并回来,而不会造成质量损失

我用.getSubimage()将图像裁剪成小块

int width = image.getWidth();
int height = image.getHeight();
int c = 4;
int r = 4;
int pWidth = width / c;
int pHeight = height / r;
int x = 0;
int y = 0;

for (int i = 0; i < c; i++) {
    y = 0;
    
    for (int j = 0; j < r; j++) {
        if ((r - j) == 1 && ((c - i) == 1)) {

            BufferedImage SubImage = image.getSubimage(x, y, width - x, height - y);
            File outfile = new File(imageName + "/" + "subPic" + i + " " + j + " " + "jpeg");
            ImageIO.write(SubImage, "jpeg", outfile);
            y += pHeight;
        } else if ((r - j) == 1) {

            BufferedImage SubImage = image.getSubimage(x, y, pWidth, height - y);
            File outfile = new File(imageName + "/" + "subPic" + i + " " + j + " " + "jpeg");
            ImageIO.write(SubImage, "jpeg", outfile);
            y += pHeight;
        } else if ((c - i) == 1) {
            BufferedImage SubImage = image.getSubimage(x, y, width - x, pHeight);
            File outfile = new File(imageName + "/" + "subPic" + i + " " + j + " " + "jpeg");
            ImageIO.write(SubImage, "jpeg", outfile);
            y += pHeight;
        } else {
            BufferedImage SubImage = image.getSubimage(x, y, pWidth, pHeight);
            y += pHeight;
            File outfile = new File(imageName + "/" + "subPic" + i + " " + j + " " + "jpeg");
            ImageIO.write(SubImage, "jpeg", outfile);
        }
    }
    x += pWidth;
}

然后使用g2d.drawimage()将它们全部合并回来

BufferedImage combinedIm = new BufferedImage(275, 183, BufferedImage.TYPE_3BYTE_BGR);
Graphics2D g2d = combinedIm.createGraphics();

int currWidth = 0;
int currHeight = 0;
int iter = -1;

for (int i = 0; i < x; i++) {
    currHeight = 0;
    
    for (int j = 0; j < y; j++) {
        iter += 1;
        g2d.drawImage(imagePieces[iter], currWidth, currHeight, null);
        currHeight += imagePieces[iter].getHeight();
    }
    currWidth += imagePieces[iter].getWidth();
}
g2d.dispose();

其中,imagePieces是一个包含主图像子图像的数组。但合并后的图像质量较差,所以我的质量检查结果总是为假

for (int x = 0; x < width; x++) {
    for (int y = 0; y < height; y++) {
        if (mainPic.getRGB(x, y) != subPic.getRGB(x, y)) {
            return false;

这是原始图像:

original

以及合并后的图像:

merged

我还可以用什么来剪切和合并图像,使其通过平等性检查,或者也许有更好的方法来检查图像是否相同


共 (1) 个答案

  1. # 1 楼答案

    我看到您正在压缩.jpg中的片段,因此需要将它们解码回来以获得rgb数据。我想你不能通过测试,因为压缩/解码后的数据丢失。 尽量不要压缩片段并以.bmp格式存储它们。或者你可以修改你的测试:用不等式代替严格的比较,这样你就可以补偿前面提到的质量损失,例如:

    final int max_diff = 3;
    for (int x = 0; x < width; x++) {
    for (int y = 0; y < height; y++) {
        if (Math.abs(mainPic.getRGB(x, y) - subPic.getRGB(x, y)) > max_diff) {
            return false;