import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageSaver {
public static void saveImage(BufferedImage image, String formatName, String filePath) {
try {
File outputFile = new File(filePath);
ImageIO.write(image, formatName, outputFile);
System.out.println("Image successfully saved to: " + filePath);
} catch (IOException e) {
System.err.println("Error saving image: " + e.getMessage());
e.printStackTrace();
}
}
public static void main(String[] args) {
// Example: Create a simple BufferedImage (replace with your actual image)
BufferedImage exampleImage = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB);
// You would typically load or create your image here
// For demonstration, let's just fill it with a color
for (int x = 0; x < exampleImage.getWidth(); x++) {
for (int y = 0; y < exampleImage.getHeight(); y++) {
exampleImage.setRGB(x, y, 0xFF0000); // Red color
}
}
// Save the BufferedImage as a PNG file
saveImage(exampleImage, "png", "output.png");
// Save the BufferedImage as a JPEG file
// Note: JPEG is a lossy format, so quality might be affected
saveImage(exampleImage, "jpg", "output.jpg");
}
}
No comments:
Post a Comment