Is there any faster way to achieve padding of pixels to a BufferedImage than drawing it centered on larger BufferedImage?
Asked
Active
Viewed 2,637 times
3
-
is the padding just for display purposes or do you need to create a new padded image? – objects Jul 20 '10 at 03:02
-
this is mostly for generating a new padded image, not just rendering it. – m0s Jul 20 '10 at 06:43
3 Answers
3
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);

Mike
- 2,393
- 3
- 25
- 37
2
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.

camickr
- 321,443
- 19
- 166
- 288
1
To defer centering until rendering, I like this approach due to finnw, where this
is 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);
}