Java原生检测图片是否jpg并将png转成jpg

2024-05-04 219点热度 0人点赞 0条评论

检测是否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);

 

admin

这个人很懒,什么都没留下

文章评论

您需要 登录 之后才可以评论