java create image

www.lautt‮ru‬i.com
java create image

To create an image in Java, you can use the BufferedImage class from the java.awt package.

Here is an example of how to create a 200x100 pixel image with a white background:

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

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedImage image = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < image.getWidth(); x++) {
            for (int y = 0; y < image.getHeight(); y++) {
                image.setRGB(x, y, Color.WHITE.getRGB());
            }
        }
        ImageIO.write(image, "png", new File("image.png"));
    }
}

This creates a new BufferedImage object with the specified width and height, and sets all pixels to white using the setRGB method. The image is then saved to a file called "image.png" using the ImageIO class.

You can also use the Graphics class from the java.awt package to draw shapes, text, and other graphics on the image. For example, to draw a red circle on the image, you can use the following code:

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

public class Main {
    public static void main(String[] args) throws Exception {
        BufferedImage image = new BufferedImage(200, 100, BufferedImage.TYPE_INT_RGB);
        Graphics g = image.getGraphics();
        g.setColor(Color.RED);
        g.fillOval(50, 25, 100, 50);
        ImageIO.write(image, "png", new File("image.png"));
    }
}

This creates a new Graphics object from the BufferedImage and uses the fillOval method to draw a red oval on the image.

Created Time:2017-11-03 00:14:52  Author:lautturi