Skip to content

Instantly share code, notes, and snippets.

@DoneSpeak
Created May 7, 2020 12:27
Show Gist options
  • Save DoneSpeak/1e50898bda18cae584aa9a2fd3075fad to your computer and use it in GitHub Desktop.
Save DoneSpeak/1e50898bda18cae584aa9a2fd3075fad to your computer and use it in GitHub Desktop.
[ImageShrinkWithDpi.java] ImageShrinkWithDpi #java #image
import java.awt.image.BufferedImage;
import java.io.IOException;
import net.coobird.thumbnailator.Thumbnails;
public class ImageShrinkWithDpi {
public static BufferedImage shrink(BufferedImage image, int imgWidthInUserSpaceUnit, int dpi) throws IOException {
int imageWidth = image.getWidth();
double scale = calculateScale(imgWidthInUserSpaceUnit, imageWidth, dpi);
if (0.0 < scale && scale < 1.0) {
return reducesImageSize(image, scale);
}
return image;
}
private static BufferedImage reducesImageSize(BufferedImage image, double scale) throws IOException {
// @formatter:off
BufferedImage thumbnail = Thumbnails.of(image)
.imageType(image.getType())
.scale(scale)
// .outputFormat(imageFormat)
.useOriginalFormat()
.asBufferedImage();
// @formatter:on
return thumbnail;
}
/**
* 用户单位的缺省值为1/72英寸,即PDF文件的页面DPI缺省为72。
*/
private static final int DEFAULT_USER_SPACE_UNIT = 72;
/**
* 根据目标dpi计算图片所需要的缩放比.
*
* @param userSpaceUnitLength
* pdf上元素长度,即用户空间长度
* @param pixelLength
* 像素长度
* @param dpi
* Dot Per Inch
* @return
*/
public static double calculateScale(float userSpaceUnitLength, int pixelLength, int dpi) {
double targetPixelLength = calculatePixel(userSpaceUnitLength, dpi);
double scale = targetPixelLength / pixelLength;
return scale;
}
/**
* 根据目标dpi计算pdf上 {@code userSpaceUnitLength} 长度转化得到的pixel值
*
* <p>
* PDF文件中同样没有任何地方存储DPI,但是所有PDF生成、处理软件都绕不开DPI:PDF文件格式规范规定,在描述页面及页面中的对象时,所有表示大小、位置的数值必须折算成“用户单位(User
* Unit)”。用户单位的缺省值为1/72英寸,即PDF文件的页面DPI缺省为72。当然这个值也可以在文件中加以更改,不过很少有人这么干。
* </p>
* <p>
* inch = userSpaceUnitLength / DPI缺省; <br/>
* pixel = inch * DPI
* </p>
*
* @param userSpaceUnitLength
* pdf上元素长度,即用户空间长度
* @param dpi
* Dot Per Inch, DPI=象素点数÷英制长度(点/英寸)
* @return
*/
public static double calculatePixel(float userSpaceUnitLength, int dpi) {
// position in user space units. 1 unit = 1/72 inch at 72 dpi
return userSpaceUnitLength / DEFAULT_USER_SPACE_UNIT * dpi;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment