1.先看效果:
2.代码
package cn.com.yuanquanyun.utils;
import cn.hutool.core.io.FileUtil;
import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class SealTransfer {
public static byte[] transfer2Byte(byte[] img) {
ByteArrayOutputStream byteArrayOutputStream = null;
InputStream is = null;
byte[] result = null;
try {
is = new ByteArrayInputStream(img);
BufferedImage bi = ImageIO.read(is);
ImageIcon imageIcon = new ImageIcon(bi);
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());
byteArrayOutputStream = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "gif", byteArrayOutputStream);//转换成byte数组
result = byteArrayOutputStream.toByteArray();
} catch (Exception e) {
// TODO Auto-generated catch block
} finally {
if (is != null) {
try {
is.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
if (byteArrayOutputStream != null) {
try {
byteArrayOutputStream.close();
} catch (IOException e) {
// TODO Auto-generated catch block
}
}
}
return result;
}
public static void main(String[] args) {
byte[] bytes = transfer2Byte(FileUtil.readBytes("C:\\Users\\root\\Desktop\\4.png"));
FileUtil.writeBytes(bytes, "C:\\Users\\root\\Desktop\\ret5.gif");
}
}
代码关键点说明:
BufferedImage bi = ImageIO.read(is);//读取图片字节流,并进行解码ImageIO.write(bufferedImage, “gif”, byteArrayOutputStream);//将处理后生成的bufferedImage按照gif格式(也可以写其他格式)进行编码存储为byte字节数组
注意:
原始图片最好印章背景是白色的,和印模颜色差别鲜明些。抠出的图会效果好些。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
文章由极客之音整理,本文链接:https://www.bmabk.com/index.php/post/142677.html