最近在做一個需求是從數(shù)據(jù)庫里面取出圖片,但是圖片都有一個白色的背景,于是項目組希望可以將圖片的白色的背景去掉。

本文為大家分享了java去除圖片中的白色背景的方法,供大家參考,具體內(nèi)容如下
如圖所示:
當(dāng)然在這個上面是看不出來的,其實第一張圖片是有一個白色的背景的,但是第二張圖片沒有,相信你理解我說的,那么這個代碼我應(yīng)該如何實現(xiàn):
package com.wdg.util;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
public class ImageUtil {
public static void main(String[] args) {
transferAlpha();
}
public static byte[] transferAlpha() {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
File file = new File("D:\\08\\11.png");
InputStream is;
try {
is = new FileInputStream(file);
// 如果是MultipartFile類型,那么自身也有轉(zhuǎn)換成流的方法:is = file.getInputStream();
BufferedImage bi = ImageIO.read(is);
Image image = (Image) bi;
ImageIcon imageIcon = new ImageIcon(image);
BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(), imageIcon.getIconHeight(),
BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
g2D.drawImage(imageIcon.getImage(), 0, 0, imageIcon.getImageObserver());
int alpha = 0;
for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage.getHeight(); j1++) {
for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage.getWidth(); j2++) {
int rgb = bufferedImage.getRGB(j2, j1);
int R = (rgb & 0xff0000) >> 16;
int G = (rgb & 0xff00) >> 8;
int B = (rgb & 0xff);
if (((255 - R) < 30) && ((255 - G) < 30) && ((255 - B) < 30)) {
rgb = ((alpha + 1) << 24) | (rgb & 0x00ffffff);
}
bufferedImage.setRGB(j2, j1, rgb);
}
}
g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());
ImageIO.write(bufferedImage, "png", new File("D:\\08\\12.png"));// 直接輸出文件
} catch (Exception e) {
e.printStackTrace();
} finally {
}
return byteArrayOutputStream.toByteArray();
}
}
本文標(biāo)題:java如何去除圖片中的白色背景-創(chuàng)新互聯(lián)
本文來源:http://chinadenli.net/article4/dpisoe.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供外貿(mào)建站、虛擬主機(jī)、網(wǎng)站策劃、靜態(tài)網(wǎng)站、網(wǎng)站維護(hù)、做網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)