Java – a bufferedimage is grayed out
I tried to gray the buffered image (instead of converting it to gray, just add gray at the top) Now I do this by using another image, making it translucent, and then overlaying it on my original image This is my current code:
package com.mypkg;
import java.awt.AlphaComposite;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.net.URL;
import javax.imageio.ImageIO;
import org.imgscalr.Scalr;
public class Overlay {
public static void main(String args[]){
URL url = null;
try{
//The gray image used for overlay
url = new URL("https://hoursofidleness.files.wordpress.com/2012/06/gray-card.jpg");
BufferedImage img1 = ImageIO.read(url);
//The original image which I want to gray out
url = new URL("http://www.staywallpaper.com/wp-content/uploads/2016/01/Colorful-Wallpaper-HD-pictures-STAY015.jpg");
BufferedImage img2 = ImageIO.read(url);
BufferedImage reImg2 = Scalr.resize(img2,Scalr.Method.BALANCED,Scalr.Mode.FIT_EXACT,150,150);
//Make the gray image,which is used as the overlay,translucent
BufferedImage transparent = new BufferedImage(img1.getWidth(),img1.getHeight(),BufferedImage.TRANSLUCENT);
Graphics2D g2d = transparent.createGraphics();
g2d.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER,(float) 0.50));
g2d.drawImage(img1,null,0);
g2d.dispose();
BufferedImage reImg1 = Scalr.resize(transparent,150);
//Merge both images
BufferedImage result = new BufferedImage(150,BufferedImage.TYPE_INT_ARGB);
Graphics2D g = result.createGraphics();
g.drawImage(reImg2,null);
g.drawImage(reImg1,null);
g.dispose();
ImageIO.write(result,"png",new File("/result.png"));
} catch(Exception e){
e.printStackTrace();
}
}
}
Is there any other way to achieve this without using additional images for superposition? Can I add a gray tone to the original image? I have read many suggestions on other posts, but none of them
thank you.
Solution
What does your method basically do:
>Loads a gray image where all pixels have the same gray. > Create a new image. > Draw a gray image on this image to make it translucent. > Draw a translucent gray image on the image you want to gray
First, there is no need to create transparent images You can use composite drawing directly on real images
Secondly, a completely gray image is no different from an ordinary rectangle. The graphics2d class has a fillRect method to draw a filled rectangle, which may be much faster than drawing an image
Therefore, after loading and zooming the original image into reimg2, you can use:
Graphics2D g2d = reImg2.createGraphics();
g2d.setColor(new Color(20,20,128));
g2d.fillRect(0,reImg2.getWidth(),reImg2.getHeight());
g2d.dispose();
That's it. Now reimg2 is dimmed and you can write it to your file Use these values – change 20s to a lower value to get a darker gray or a higher value (up to 255) to get a lighter gray For more gray images, change 128 (50% alpha) to a higher value, or change a lower value for less gray images
