背景
在實現圖片硬章插入文檔的時候,遇到了如下的問題。 給出的硬章的背景是白色的,並不是想要的透明色。這樣有什麼影響呢?這裏貼一個圖片可以進行觀察。
你覺得對於硬章來說是透明色更接近現實情況呢,還是直接貼圖好呢?
思路介紹
對於硬章圖片,需要把他的白色背景,或者說是淺色背景扣調,也就是在白色或者接近白色的地方(255 255 255)給他的alpha 通道設置成0,對於有信息的地方(深色)alpha設置255,這樣就是實現了硬章摳圖。
避坑
如果是用opencv 實現的話也沒有什麼好寫的,這裏主要使用java 實現了摳圖的過程,並在android中重寫了該方法。
在java中是無法給colorModel 是RGB圖片進行設置透明通道的,這裏需要把圖片變成ARGB的,這裏可以通過Graphics2D進行轉化
基本流程
- 讀取圖片
- 判斷顏色模式,並統一到ARGB
- 遍歷像素
- 淺色點設置透明通道爲0
代碼講解
java實現
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
/**
* @name SignImage
* @date 2020/6/3 20:28
*/
public class SignImage {
public static void main(String[] args) throws IOException {
String filePath = "D://sign.jpg";
//讀取圖片
BufferedImage imageTmp = ImageIO.read(new File(filePath));
int alphaLocal = imageTmp.getColorModel().getAlpha(0);
//統一圖片到argb
if(imageTmp.getColorModel().getNumComponents() == 3){
BufferedImage teemp = new BufferedImage(imageTmp.getWidth(),imageTmp.getHeight(),6);
//6 是argb的意思
//藉助graphics 轉argb
Graphics2D graphics2D = DrawPictureUitl.getGraphics(teemp,
imageTmp.getWidth(),imageTmp.getHeight(),1);
graphics2D.drawImage(imageTmp,0,0,null);
imageTmp = teemp;
graphics2D.dispose();
}
if ( alphaLocal == 255){
int alpha = 0;
//遍歷像素。可以並行
for (int j1 = imageTmp.getMinY(); j1 < imageTmp
.getHeight(); j1++) {
for (int j2 = imageTmp.getMinX(); j2 < imageTmp
.getWidth(); j2++) {
int rgb = imageTmp.getRGB(j2, j1);
if (colorInRange(rgb)){
alpha = 0;
}
else{
alpha = 250;
}
rgb = (alpha << 24) | (rgb & 0x00ffffff);
imageTmp.setRGB(j2, j1, rgb);
}
}
}
//保存圖片
ImageIO.write(imageTmp, "png", new File("d://test.png"));
}
//檢測顏色是否需要加透明通道
public static boolean colorInRange(int color) {
int red = (color & 0xff0000) >> 16;
int green = (color & 0x00ff00) >> 8;
int blue = (color & 0x0000ff);
if (red >= 230 && green >= 230 && blue >= 230)
{return true;}
return false;
}
}
對於android 來說,處理的是bitmap ,原理是一樣的
//把白色轉換成透明
public static Bitmap getImageToChange(Bitmap mBitmap) {
Bitmap createBitmap = Bitmap.createBitmap(mBitmap.getWidth(), mBitmap.getHeight(), Bitmap.Config.ARGB_8888);
if (mBitmap != null) {
int mWidth = mBitmap.getWidth();
int mHeight = mBitmap.getHeight();
for (int i = 0; i < mHeight; i++) {
for (int j = 0; j < mWidth; j++) {
int color = mBitmap.getPixel(j, i);
int g = Color.green(color);
int r = Color.red(color);
int b = Color.blue(color);
int a = Color.alpha(color);
if(g>=250&&r>=250&&b>=250){
a = 0;
}
color = Color.argb(a, r, g, b);
createBitmap.setPixel(j, i, color);
}
}
}
return createBitmap;
}