3
4

More than 5 years have passed since last update.

画像ファイルの形式を変更する

Posted at

imageIOを使ってpngやgifをjpegに変更するプログラム。

import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.imageio.ImageIO;

String from = "変換前の画像パス";
String to   = "変換後の画像パス";
try {
    BufferedImage image = ImageIO.read(new File(from));
    BufferedImage tmp = new BufferedImage(image.getWidth(), image.getHeight(), BufferedImage.TYPE_INT_RGB);
    Graphics2D off = tmp.createGraphics();
    off.drawImage(image, 0, 0, Color.WHITE, null);
    ImageIO.write(tmp, "jpg", new File(to));
} catch (Exception e) {
    System.out.println("error");
}

おまけ

ファイルの拡張子を変える方法(jpgに変更する例)。

import org.apache.commons.io.FilenameUtils;

String from; //変更前のパス
String to;   //変更後のパス

String to = String.format("%s%s.%s", FilenameUtils.getFullPath(to), FilenameUtils.getBaseName(from), "jpg");
3
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
4