A small Java program to generate transparent images (for dynamic background colours)
Somebody requested me to generate a web page with a wall background that should change the wall colour based on the user's desire.
I thought a transparency-enabled background will suffice, with a dynamic background of the image.
Steps:
- Take the background image from my customer;
- Generate a mask image as a copy of the background image, and remove the area (set it to black) where I want to have transparency;
- Run the Java program that is written below;
- Use the final result image and put it in a web page.
ImageTansparency.java
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageTransparency {
private static BufferedImage original;
private static BufferedImage mask;
private static BufferedImage result;
public static void main(String[] args) throws IOException {
String folder = "C:\\Users\\DragosMateiS\\Desktop\\";
original = ImageIO.read(new File(folder + "wall test image.jpg"));
mask = ImageIO.read(new File(folder + "wall test image - mask.jpg"));
result = new BufferedImage(original.getWidth(), original.getHeight(),
BufferedImage.TYPE_INT_ARGB);
process();
ImageIO.write(result, "png", new File(folder
+ "wall test image - result.png"));
}
private static void process() {
int width = original.getWidth();
int height = original.getHeight();
for (int x = 0; x < width; x++)
for (int y = 0; y < height; y++) {
Color originalRGB = new Color(original.getRGB(x, y));
Color maskRGB = new Color(mask.getRGB(x, y));
int argb = originalRGB.getRGB();
int r = maskRGB.getRed();
int g = maskRGB.getGreen();
int b = maskRGB.getBlue();
int balance = r * 2 + b + g * 4;
int alpha=balance/7;
if (alpha >= 30)
argb &= 0x00ffffff + (alpha << 24);
result.setRGB(x, y, argb);
}
}
}