使用Java裁剪/修剪具有空白空间的JPG文件

是否有一个框架可以删除图像的空白区域(矩形)。我们很遗憾地从技术图纸中创建了图像缩略图。我们将PDF转换为SVG,然后转换为JPG。技术图纸通常很小,现在放在缩略图的左上角:

+---------+----------------------+

| | |

| (image) | |

| | |

+---------+ |

| |

| |

| |

| |

| (empty space) |

| |

| |

+--------------------------------+

那么,如何轻松删除空白区域并缩小JPG文件?

回答:

如该线程所示,可以在JAI中完成。或者这是我刚刚编写的一些Java代码,可用于执行此操作:

public class TrimWhite {

private BufferedImage img;

public TrimWhite(File input) {

try {

img = ImageIO.read(input);

} catch (IOException e) {

throw new RuntimeException( "Problem reading image", e );

}

}

public void trim() {

int width = getTrimmedWidth();

int height = getTrimmedHeight();

BufferedImage newImg = new BufferedImage(width, height,

BufferedImage.TYPE_INT_RGB);

Graphics g = newImg.createGraphics();

g.drawImage( img, 0, 0, null );

img = newImg;

}

public void write(File f) {

try {

ImageIO.write(img, "bmp", f);

} catch (IOException e) {

throw new RuntimeException( "Problem writing image", e );

}

}

private int getTrimmedWidth() {

int height = this.img.getHeight();

int width = this.img.getWidth();

int trimmedWidth = 0;

for(int i = 0; i < height; i++) {

for(int j = width - 1; j >= 0; j--) {

if(img.getRGB(j, i) != Color.WHITE.getRGB() &&

j > trimmedWidth) {

trimmedWidth = j;

break;

}

}

}

return trimmedWidth;

}

private int getTrimmedHeight() {

int width = this.img.getWidth();

int height = this.img.getHeight();

int trimmedHeight = 0;

for(int i = 0; i < width; i++) {

for(int j = height - 1; j >= 0; j--) {

if(img.getRGB(i, j) != Color.WHITE.getRGB() &&

j > trimmedHeight) {

trimmedHeight = j;

break;

}

}

}

return trimmedHeight;

}

public static void main(String[] args) {

TrimWhite trim = new TrimWhite(new File("...\\someInput.bmp"));

trim.trim();

trim.write(new File("...\\someOutput.bmp"));

}

}

以上是 使用Java裁剪/修剪具有空白空间的JPG文件 的全部内容, 来源链接: utcz.com/qa/415257.html

回到顶部