Java 9 多分辨率图像 API

Java 9 定义多分辨率图像 API,开发者可以很容易的操作和展示不同分辨率的图像了。

以下是多分辨率图像的主要操作方法:

  • Image getResolutionVariant(double destImageWidth, double destImageHeight) − 获取特定分辨率的图像变体-表示一张已知分辨率单位为DPI的特定尺寸大小的逻辑图像,并且这张图像是最佳的变体。。

  • ListJava 9 多分辨率图像 API - 图1 getResolutionVariants() − 返回可读的分辨率的图像变体列表。

实例

  1. import java.io.IOException;
  2. import java.net.URL;
  3. import java.net.MalformedURLException;
  4. import java.util.ArrayList;
  5. import java.util.List;
  6. import java.awt.Image;
  7. import java.awt.image.MultiResolutionImage;
  8. import java.awt.image.BaseMultiResolutionImage;
  9. import javax.imageio.ImageIO;
  10. public class Tester {
  11. public static void main(String[] args) throws IOException, MalformedURLException {
  12. List<String> imgUrls = List.of("https://www.jishuchi.com/static/images/logo.png", "https://www.jishuchi.com/uploads/201908/15b8e7c23616a965.jpeg", "https://www.jishuchi.com/uploads/201908/15bf92daf9d2194e.png");
  13. List<Image> images = new ArrayList<Image>();
  14. for (String url : imgUrls) {
  15. images.add(ImageIO.read(new URL(url)));
  16. }
  17. // 读取所有图片
  18. MultiResolutionImage multiResolutionImage =
  19. new BaseMultiResolutionImage(images.toArray(new Image[0]));
  20. // 获取图片的所有分辨率
  21. List<Image> variants = multiResolutionImage.getResolutionVariants();
  22. System.out.println("Total number of images: " + variants.size());
  23. for (Image img : variants) {
  24. System.out.println(img);
  25. }
  26. // 根据不同尺寸获取对应的图像分辨率
  27. Image variant1 = multiResolutionImage.getResolutionVariant(156, 45);
  28. System.out.printf("\nImage for destination[%d,%d]: [%d,%d]",
  29. 156, 45, variant1.getWidth(null), variant1.getHeight(null));
  30. Image variant2 = multiResolutionImage.getResolutionVariant(311, 89);
  31. System.out.printf("\nImage for destination[%d,%d]: [%d,%d]", 311, 89,
  32. variant2.getWidth(null), variant2.getHeight(null));
  33. Image variant3 = multiResolutionImage.getResolutionVariant(622, 178);
  34. System.out.printf("\nImage for destination[%d,%d]: [%d,%d]", 622, 178,
  35. variant3.getWidth(null), variant3.getHeight(null));
  36. Image variant4 = multiResolutionImage.getResolutionVariant(300, 300);
  37. System.out.printf("\nImage for destination[%d,%d]: [%d,%d]", 300, 300,
  38. variant4.getWidth(null), variant4.getHeight(null));
  39. }
  40. }