Java BufferedImage Population

Is there any faster way to achieve pixel filling in a BufferedImage than drawing it in the center using a BufferedImage?

+3
source share
3 answers

BufferedImage has a constructor where you can specify a WriteableRaster.

When choosing a default buffered image, saving each pixel in an int, it uses IntegerInterleavedRaster.

In ColorModel, you can use ColorModel.getRGBDefault ().

int imageWidth = 638, imageHeight = 480;
int dataImageWidth = 640;

SampleModel sm = new SinglePixelPackedSampleModel(TYPE_INT, imageWidth, imageHeight, dataImageWidth, new int[] { 0xff0000, 0xff00, 0xff });
DataBuffer db = new DataBufferInt(dataImageWidth * imageHeight);
WritableRaster r = Raster.createWritableRaster(sm, db, new Point());
BufferedImage image = new BufferedImage(ColorModel.getRGBDefault(), r, false, null);

Pay attention to scanlineStride in SinglePixelPackedSampleModel (second last parameter).

Another simpler approach is to use the BufferedImage getSubimage method.

BufferedImage fullImage = new BufferedImage(dataImageWidth, imageHeight);
BufferedImage subImage = fullImage.getSubimage(0, 0, imageWidth, imageHeight);
+2
source

ImageIcon, BufferedImage, Icon JLabel. , .

+2

To delay centering until rendering, I like this approach because of finnw , where thisis a suitable component:

private BufferedImage image;
....
@Override
public void paintComponent(Graphics g) {
    super.paintComponent(g);
    Graphics2D g2d = (Graphics2D) g;
    g2d.translate(this.getWidth() / 2, this.getHeight() / 2);
    g2d.translate(-image.getWidth() / 2, -image.getHeight() / 2);
    g2d.drawImage(image, 0, 0, null);
}
+1
source

Source: https://habr.com/ru/post/1755403/


All Articles