检测是否jpg代码:
public static boolean isJpg(File file) throws IOException { try (InputStream is = new FileInputStream(file)) { ImageInputStream iis = ImageIO.createImageInputStream(is); Iterator<ImageReader> readers = ImageIO.getImageReaders(iis); if (!readers.hasNext()) { return false; } String formatName = readers.next().getFormatName(); return "jpeg".equalsIgnoreCase(formatName) || "jpg".equalsIgnoreCase(formatName); } }
转成jpg:
public static BufferedImage toJpg(BufferedImage image) { int width = image.getWidth(); int height = image.getHeight(); // TYPE_INT_ARGB是png格式 BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); Graphics2D g2 = newImage.createGraphics(); g2.drawImage(image, 0, 0, null); g2.dispose(); return newImage; }
另外在使用 ImageIO.write()
方法进行图像写入时,也要注意指定正确的格式参数:
// 写入 JPEG 格式 ImageIO.write(newImage, "jpg", file); // 写入 PNG 格式 ImageIO.write(newImage, "png", file);
文章评论