I'm working with Java to store and modify .jpg images, (not Android or Swing). I want to transform an image with a new dimension keeping the aspect ratio and filling the background with white color if the new dimension is not proportional to the original image.
BufferedImage image = /*Here i read from disk and load the image */;
image = resizeImage(image, newWidth, newHeight);
ImageIO.write(image, extension, new File(filename + "_" + page + "." + extension));
The function I'm trying to implement is resizeImage: in the example resizes the image but it doesn't keep the aspect ratio.
private static BufferedImage resizeImage(BufferedImage originalImage, int width, int height) {
BufferedImage resizedImage = new BufferedImage(width, height, originalImage.getType());
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, width, height, null);
g.dispose();
return resizedImage;
}
I think a picture will be more illustrative of what I'm asking for:
If the original image is 200x200 and is asked to resize to 400x300 the result should be a picture with white margin and the original picture resized inside. In this example should be 300x300.
The problem is not how to resize, it's how to fill the remaining image with white and the original resized image on the center of it.
This code worked for me:
private static BufferedImage resizeImage(BufferedImage originalImage, int newWidth, int newHeight) {
BufferedImage resizedImage = new BufferedImage(newWidth, newHeight, originalImage.getType());
Graphics2D graphics = resizedImage.createGraphics();
graphics.setColor(Color.WHITE);
// fill the entire picture with white
graphics.fillRect(0, 0, newWidth, newHeight);
int maxWidth = 0;
int maxHeight = 0;
// go along the width and height in increments of 1 until one value is equal to the specified resize value
while (maxWidth <= newWidth && maxHeight <= newHeight)
{
++maxWidth;
++maxHeight;
}
// calculate the x value with which the original image is centred
int centerX = (resizedImage.getWidth() - maxWidth) / 2;
// calculate the y value with which the original image is centred
int centerY = (resizedImage.getHeight() - maxHeight) / 2;
// draw the original image
graphics.drawImage(originalImage, centerX, centerY, maxWidth, maxHeight, null);
graphics.dispose();
return resizedImage;
}
Before:
After:
Related
I have two images with different sizes. I want to merge these two images so that the front images overlays correctly the background image.
background (width:144 height:147):
front: (width:227 height:238)
Currently my result looks like this, but i need it to overlay perfectly
My approach is.
I am resizing the smaller image to the bigger one. For that I am using the a external lib named imgscalr (https://mvnrepository.com/artifact/org.imgscalr/imgscalr-lib/4.2).
As you can see result image is not correct, so I tried to scale the front image so that it overlay the background, also I changed the root of the x / y when I draw the front image on the background but i still have a difference. Any idea how I can merge the two images, so that the strokes image (front) overlays the background.
public static byte[] mergeBackgroundWithStrokes(byte[] backgroundImage, byte[] frontImage)
throws IOException, PDProcessingException {
Path backgroundfile = readAllBytes(backgroundImage, "background");
Path outputFile = Files.createTempFile("output", ".png");
BufferedImage backgroundBuffImg = ImageIO.read(backgroundfile.toFile());
BufferedImage frontBuffImg = makeColorTransparent(frontImage, Color.WHITE);
int width = Math.max(backgroundBuffImg.getWidth(), frontBuffImg.getWidth());
int height = Math.max(backgroundBuffImg.getHeight(), frontBuffImg.getHeight());
backgroundBuffImg = resize(backgroundBuffImg, width, height);
//scaling front image
int scaledWidth = (int) ((width));
int scaledHeight = (int) ((height) * 1.02);
frontBuffImg = resize(frontBuffImg, scaledWidth, scaledHeight);
BufferedImage newImage = mergeImages(backgroundBuffImg, frontBuffImg);
ImageIO.write(newImage, "PNG", outputFile.toFile());
return Files.readAllBytes(outputFile);
}
public static BufferedImage resize(BufferedImage img, int width, int height)
{
if (img.getWidth() == width && img.getHeight() == height) {
return img;
} else {
return Scalr.resize(img, width, height);
}
}
public static BufferedImage mergeImages(BufferedImage background, BufferedImage front) {
int width = background.getWidth();
int height = background.getHeight();
BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics g = newImage.getGraphics();
g.drawImage(background, 0, 0, null);
g.drawImage(front, 15, -10, background.getWidth(), background.getHeight(), 0, 0, width, height, null);
return newImage;
}
Here you can see the complete class: https://pastebin.com/F4VrBwRv
I want to draw a rectangle around BufferedImage so it will create a border like frame.
So I load 2 BufferedImage:
BufferedImage a = ImageIO.read(new File(aPath));
BufferedImage b = ImageIO.read(new File(bPath));
And send it for drawing:
private void drawImageBorder(BufferedImage imageWithoutBorder) {
Graphics2D graph = imageWithoutBorder.createGraphics();
graph.setColor(Color.BLACK);
//create a black Rectangle - 1px bigger the original image
graph.fill(new Rectangle(imageWithoutBorder.getMinX(), imageWithoutBorder.getMinY(), imageWithoutBorder.getWidth() + 1, imageWithoutBorder.getHeight() +1));
//draw the image inside it
graph.drawImage(imageWithoutBorder, 0, 0, null);
graph.dispose();
}
For some reason it does nothing, there are similer questions like drawing-filled-rectangle-over-a-bufferedimage but I could not finnd helpful answers.
Thanks.
Almost right, but for the enlarged size and positioning.
BufferedImage image = ImageIO.read(new File(imagePath));
int w = image.getWidth();
int h = Image.getHeight();
int border = 1;
BufferedImage framedImage = new BufferedImage(w + 2*border, h + 2*border, image.getType());
Graphics2D graph = framedImage.createGraphics();
graph.setColor(Color.BLACK);
graph.fill(new Rectangle(0, 0, w + 2*border, h + 2*border));
graph.drawImage(image, border, border, null);
graph.dispose();
Possible reason can be, that you don't persist the changes made to the image, for example writing them back into an image file with ImageIO.write.
In a project, I want to simultaneously resize and change the opacity of an image. So far I think I've got the resizing down. I use a method defined like so to accomplish the resizing:
public BufferedImage resizeImage(BufferedImage originalImage, int type){
initialWidth += 10;
initialHeight += 10;
BufferedImage resizedImage = new BufferedImage(initialWidth, initialHeight, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, initialWidth, initialHeight, null);
g.dispose();
return resizedImage;
}
I got this code from here. What I can't find a solution to is changing the opacity. That's what I'm wondering how to do (if it's possible at all). Thanks in advance.
UPDATE:
I tried this code to display a picture of a circle with transparent insides and outsides (see below image) growing and becoming less and less opaque, but it didn't work. I'm not sure what's wrong. All the code is in a class called Animation
public Animation() throws IOException{
image = ImageIO.read(new File("circleAnimation.png"));
initialWidth = 50;
initialHeight = 50;
opacity = 1;
}
public BufferedImage animateCircle(BufferedImage originalImage, int type){
//The opacity exponentially decreases
opacity *= 0.8;
initialWidth += 10;
initialHeight += 10;
BufferedImage resizedImage = new BufferedImage(initialWidth, initialHeight, type);
Graphics2D g = resizedImage.createGraphics();
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity));
g.drawImage(originalImage, 0, 0, initialWidth, initialHeight, null);
g.dispose();
return resizedImage;
}
I call it like this:
Animation animate = new Animation();
int type = animate.image.getType() == 0? BufferedImage.TYPE_INT_ARGB : animate.image.getType();
BufferedImage newImage;
while(animate.opacity > 0){
newImage = animate.animateCircle(animate.image, type);
g.drawImage(newImage, 400, 350, this);
}
first make sure the type you're passing into to method contains an alpha channel, like
BufferedImage.TYPE_INT_ARGB
and then just before you paint the new image, call the Graphics2D method setComposite like so:
float opacity = 0.5f;
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, opacity));
that will set the drawing opacity to 50%.
I'm trying to resize an image to 50 * 50 pixels. Im taking the images, from their path stored in a Database. I have no problem getting the images and displaying them. I'm just wondering at what point should I try resize the images. Should it be when I get the image as a buffered image, or just try to resize the icon?
while (rs.next()) {
i = 1;
imagePath = rs.getString("path");
System.out.println(imagePath + "\n");
System.out.println("TESTING - READING IMAGE");
System.out.println(i);
myImages[i] = ImageIO.read(new File(imagePath));
**resize(myImages[i]);**
imglab[i] = new JLabel(new ImageIcon(myImages[i]));
System.out.println(i);
imgPanel[i]= new JPanel();
imgPanel[i].add(imglab[i]);
loadcard.add(imgPanel[i], ""+i);
i++;
The above code is retrieving the image and assigning it to an ImageIcon, then JLabel. I have attempted to resize the buffered image, by using the below resize method. Could you guys, shed any light on why this isn't working for me? Not getting any errors, just the image remains its original size.
public static BufferedImage resize(BufferedImage img) {
int w = img.getWidth();
int h = img.getHeight();
int newH = 50;
int newW = 50;
BufferedImage dimg = dimg = new BufferedImage(newW, newH, img.getType());
Graphics2D g = dimg.createGraphics();
System.out.println("Is this getting here at all " + dimg);
g.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
g.drawImage(img, 0, 0, newW, newH, 0, 0, w, h, null);
g.dispose();
return dimg;
}
You are calling resize() on each image, but not replacing the images in the array. So the output of resize() is being thrown away:
myImages[i] = ImageIO.read(new File(imagePath)); // create an image
resize(myImages[i]); // returns resized img, but doesn't assign it to anything
imglab[i] = new JLabel(new ImageIcon(myImages[i])); // uses _original_ img
You need to change the middle line to:
myImages[i] = resize(myImages[i]);
to make this work.
I have snippet of code that I am using for the purpose of resizing an image to a curtain size (I want to change the resolution to something like 200 dpi). Basically the reason I need it is because I want to display the image that the user have picked (somewhat large) and then if the user approves I want to display the same image in a different place but using a smaller resolution. Unfortunately, if I give it a large image nothing appears on the screen. Also, if I change
imageLabel.setIcon(newIcon);
to
imageLabel.setIcon(icon);
I get the image to display but not in the correct resolution that's how I know that I have a problem inside this snipper of code and not somewhere else.
Image img = icon.getImage();
BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
boolean myBool = g.drawImage(img, 0, 0, 100, 100, null);
System.out.println(myBool);
ImageIcon newIcon = new ImageIcon(bi);
imageLabel.setIcon(newIcon);
submitText.setText(currentImagePath);
imageThirdPanel.add(imageLabel);
You don't really have to care about the details of scaling images. The Image class has already a method getScaledInstance(int width, int height, int hints) designed for this purpose.
Java documentation says:
Creates a scaled version of this image. A new Image object is returned
which will render the image at the specified width and height by
default. The new Image object may be loaded asynchronously even if the
original source image has already been loaded completely. If either
the width or height is a negative number then a value is substituted
to maintain the aspect ratio of the original image dimensions.
And you can use it like this:
// Scale Down the original image fast
Image scaledImage = imageToScale.getScaledInstance(newWidth, newHighth, Image.SCALE_FAST);
// Repaint this component
repaint();
Check this for a complete example.
Here is my solution:
private BufferedImage resizeImage(BufferedImage originalImage, int width, int height, int type) throws IOException {
BufferedImage resizedImage = new BufferedImage(width, height, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, width, height, null);
g.dispose();
return resizedImage;
}
Try this CODE to resize image :
public static Image scaleImage(Image original, int newWidth, int newHeight) {
//do nothing if new and old resolutions are same
if (original.getWidth() == newWidth && original.getHeight() == newHeight) {
return original;
}
int[] rawInput = new int[original.getHeight() * original.getWidth()];
original.getRGB(rawInput, 0, original.getWidth(), 0, 0, original.getWidth(), original.getHeight());
int[] rawOutput = new int[newWidth * newHeight];
// YD compensates for the x loop by subtracting the width back out
int YD = (original.getHeight() / newHeight) * original.getWidth() - original.getWidth();
int YR = original.getHeight() % newHeight;
int XD = original.getWidth() / newWidth;
int XR = original.getWidth() % newWidth;
int outOffset = 0;
int inOffset = 0;
for (int y = newHeight, YE = 0; y > 0; y--) {
for (int x = newWidth, XE = 0; x > 0; x--) {
rawOutput[outOffset++] = rawInput[inOffset];
inOffset += XD;
XE += XR;
if (XE >= newWidth) {
XE -= newWidth;
inOffset++;
}
}
inOffset += YD;
YE += YR;
if (YE >= newHeight) {
YE -= newHeight;
inOffset += original.getWidth();
}
}
return Image.createRGBImage(rawOutput, newWidth, newHeight, false);
}
Another example is given here :
2D-Graphics/LoadImageandscaleit.htm">http://www.java2s.com/Tutorial/Java/0261_2D-Graphics/LoadImageandscaleit.htm
http://www.java2s.com/Code/JavaAPI/java.awt/ImagegetScaledInstanceintwidthintheightinthints.htm