Java操作透明图片并保持背景透明
最近的一个需求,需要对背景为透明的图片加汉字,加完后会出现背景变黑的情况,附上解决方案
public static void pressText2(String sourceImg,String targetImg) {
try {
File file = new File(sourceImg);
File targetfile = new File(targetImg);
Image image = ImageIO.read(file);
int width = image.getWidth(null);
int height = image.getHeight(null);
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bufferedImage.createGraphics();
bufferedImage = g.getDeviceConfiguration()
.createCompatibleImage(width, height, Transparency.TRANSLUCENT);
g = bufferedImage.createGraphics();
g.drawImage(image, 0, 0, null);
g.setColor(Color.BLACK);
g.drawString("wudididi",20,20);
ImageIO.write(bufferedImage, "png", targetfile);
} catch (Exception e) {
e.printStackTrace();
}
}
这样新的图片会有加的汉字并且保持背景透明
Java图片背景透明及透明度处理
如题,以下为通过java实现的针对图片的背景透明及透明度处理,供大家需要时参考:
public static void transparentImage(String srcFile,String desFile,int alpha,String formatName) throws IOException{
BufferedImage temp = ImageIO.read(new File(srcFile));//取得图片
transparentImage(temp, desFile, alpha, formatName);
}
public static void transparentImage(BufferedImage srcImage,
String desFile, int alpha, String formatName) throws IOException {
int imgHeight = srcImage.getHeight();//取得图片的长和宽
int imgWidth = srcImage.getWidth();
int c = srcImage.getRGB(3, 3);
//防止越位
if (alpha < 0) {
alpha = 0;
} else if (alpha > 10) {
alpha = 10;
}
BufferedImage bi = new BufferedImage(imgWidth, imgHeight,
BufferedImage.TYPE_4BYTE_ABGR);//新建一个类型支持透明的BufferedImage
for(int i = 0; i < imgWidth; ++i)//把原图片的内容复制到新的图片,同时把背景设为透明
{
for(int j = 0; j < imgHeight; ++j)
{
//把背景设为透明
if(srcImage.getRGB(i, j) == c){
bi.setRGB(i, j, c & 0x00ffffff);
}
//设置透明度
else{
int rgb = bi.getRGB(i, j);
rgb = ((alpha * 255 / 10) << 24) | (rgb & 0x00ffffff);
bi.setRGB(i, j, rgb);
}
}
}
ImageIO.write(bi, StringUtils.isEmpty(formatName)?FORMAT_PNG:formatName, new File(desFile));
}
以上为个人经验,希望能给大家一个参考,也希望大家多多支持编程网。