最近在做一個需求是從數(shù)據(jù)庫里面取出圖片,但是圖片都有一個白色的背景,于是項目組希望可以將圖片的白色的背景去掉。
本文為大家分享了java去除圖片中的白色背景的方法,供大家參考,具體內(nèi)容如下
如圖所示:
當然在這個上面是看不出來的,其實第一張圖片是有一個白色的背景的,但是第二張圖片沒有,相信你理解我說的,那么這個代碼我應(yīng)該如何實現(xiàn):
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
|
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(); } } |
代碼是對圖片進行操作,復(fù)制過去就可以直接實現(xiàn)你的功能了。
以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:https://blog.csdn.net/datouniao1/article/details/80061735