Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java BufferedImage padding

Is there any faster way to achieve padding of pixels to a BufferedImage than drawing it centered on larger BufferedImage?

like image 511
m0s Avatar asked Sep 11 '26 12:09

m0s


2 Answers

BufferedImage has a constructor where you get to specify a WriteableRaster.

Picking at the a default buffered image, storing each pixel in an int, it uses an IntegerInterleavedRaster.

The 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);

Notice the scanlineStride in SinglePixelPackedSampleModel (second last parameter).

Another much simpler approach is to use BufferedImage's getSubimage method.

BufferedImage fullImage = new BufferedImage(dataImageWidth, imageHeight);
BufferedImage subImage = fullImage.getSubimage(0, 0, imageWidth, imageHeight);
like image 131
Mike Avatar answered Sep 14 '26 02:09

Mike


Create an ImageIcon using the BufferedImage and add the Icon to a JLabel. Then you can just add a Border to the label to get your desired padding.

like image 38
camickr Avatar answered Sep 14 '26 00:09

camickr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!