一、实现方法
字符画实际上是将图片的每一个像素点,按一定的标准(如灰度值等)替换为字符(如图所示,图示为黑色背景,白色字体)。
二、图片转字符画 实现过程
①读取图片(这里使用java.jwt自带的BufferedImage对象读取)
/** 获取最原生的BufferedImage对象 */
public static BufferedImage getBufferedImage(final String src) throws FileNotFoundException, IOException {
return ImageIO.read(new FileInputStream(new File(src.trim())));
}
②对图片进行处理(如压缩、灰度化、二值化等),一般来说,先二值/灰度化后再压缩,效果比较好,当然具体情况具体分析
下面贴上代码
/**
* 按设置的宽度高度比例压缩图片文件,如果width和height都大于0,则以此为基准进行压缩(可能造成图片变型)
*
* @param oldFile
* 要进行压缩的文件全路径
* @param newFile
* 新文件
* @param width
* 宽度
* @param height
* 高度
* @return 返回压缩后的文件的全路径
*/
public static BufferedImage zipImageFileWithRate(BufferedImage image, int width, int height) {
if (image == null) {
return null;
}
if(width<=0&&height<=0){
return image;
}
/* 对服务器上的临时文件进行处理 */
/* 按比例压缩 */
int w = image.getWidth(null);
int h = image.getHeight(null);
double bili;
if (width > 0&&height<=0) {
bili = width / (double) w;
height = (int) (h * bili);
} else if (height > 0&&width<=0) {
bili = height / (double) h;
width = (int) (w * bili);
}
BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D graphics = buffImg.createGraphics();
graphics.getFontRenderContext();
graphics.setBackground(new Color(255, 255, 255));
graphics.setColor(new Color(255, 255, 255));
graphics.fillRect(0, 0, width, heigh