13

I am working on creating an online image editing tool.Looking for some refernce how can I add an image with white space on right side.For example see this image enter image description here

Pit Digger
  • 9,618
  • 23
  • 78
  • 122

3 Answers3

17

Presumably, you want to create a new image from an existing image, where the new image has white space on the left and right?

Suppose the unpadded image was a BufferedImage and is called 'image'. Suppose the amount of whitespace you want on each side is 'w'. What you want to do is create a new BufferedImage wider than the original, then paint the entire thing white, and finally draw the smaller image on top of it:

BufferedImage newImage = new BufferedImage(image.getWidth() + 2 * w, image.getHeight(), image.getType());

Graphics g = newImage.getGraphics();

g.setColor(Color.white);
g.fillRect(0, 0, image.getWidth() + 2 * w, image.getHeight());
g.drawImage(image, w, 0, null);
g.dispose();
Andrii Abramov
  • 10,019
  • 9
  • 74
  • 96
toadaly
  • 647
  • 3
  • 6
3

If anyone comes upon a similar problem, I would definitively recommend imgScalr. You can add padding with literally one line imageSource= Scalr.pad(imageSource,pad,Color.White);.

peterkodermac
  • 318
  • 5
  • 13
  • Thank you for the great tip! – narzero Feb 27 '16 at 16:40
  • 3
    imgScalr seems to be a nice library, but I do not see any way to pad only 2 borders (i.e., left-right side); padding is always added to all 4 borders. Of course, you can crop afterwards to remove the padding from top-bottom borders, but this is not very clean and readable. – Rauni Lillemets Aug 16 '17 at 12:43
2

Create a new BufferedImage object of the right size; use Graphics.fillRect() to paint it white; draw the image into the top-left corner with drawImage(); then save your new image.

Ernest Friedman-Hill
  • 80,601
  • 10
  • 150
  • 186