[英]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.