[英]Scaling an image with Java
我创建了一个图像,该图像是 PDF 的提取物,并制作了一个带有 tesseract 的 OCR。 在决定更改图像的 dpi 之前,一切正常。 我希望这样做会出错,我试图重新调整我的图像以使我的 OCR 再次正常工作。
我不知道如何重新调整图像。 我知道 BufferedImage class 有一些方法,但我找不到动态重新缩放它的方法。
我不知道我是否清楚,但想象一个 300 dpi 的图像。 如果我想将其更改为 600,我必须重新调整我的图像以使我的 OCR 再次工作,我的问题是如何动态地重新调整它? 原始 dpi 和新的 dpi 之间是否存在某种比例,我可以使用它来获得新的宽度和高度? 或者是其他东西?
为了帮助您理解我,这里是我的代码:
public double ratioDPI() {
int ratio = 0;
int minimal_dpi = 300;
int dpi = ERXProperties.intForKey("dpi.image");
return ratio = (dpi/minimal_dpi);
}
public BufferedImage rescale(BufferedImage img) {
int width_img = img.getWidth();
int height_img = img.getHeight();
double factor_width = ERXProperties.doubleForKey("factor.size.width.image.republique.francaise");
double factor_height = ERXProperties.doubleForKey("factor.size.height.image.republique.francaise");
return (BufferedImage) img.getScaledInstance((int)(width_img*ratio), (int)(height_img*ratio), BufferedImage.SCALE_SMOOTH);
}
例如,如果更改图像的 DPI,则在将其输出到打印机时会更改尺寸。 如果将 DPI 从 300 增加到 600,output 中的图像只占一半宽度和一半高度。 如果现在调整图片大小只占用更多的memory,图片质量不会更好。
对于缩放,最好使用AffineTransform
,因此您可以对图像进行bilinear
过滤,以使像素化不那么明显:
A缩放function:
public static BufferedImage scale(BufferedImage source, double scale, boolean bilinearFiltering){
try{
BufferedImage destination = new BufferedImage((int)(source.getWidth() * scale), (int)(source.getHeight() * scale), source.getType());
AffineTransform at = new AffineTransform();
at.scale(scale, scale);
AffineTransformOp scaleOp = new AffineTransformOp(at, getInterpolationType(bilinearFiltering));
return scaleOp.filter(source, destination);
}
catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static int getInterpolationType(boolean bilinearFiltering){
return bilinearFiltering ? AffineTransformOp.TYPE_BILINEAR : AffineTransformOp.TYPE_NEAREST_NEIGHBOR;
}
也许这对你来说是一个解决方案。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.