java实现图像灰度化

  /*在研究Java实现将一张图片转成字符画的时候,发现将图像转化字符串是根据照片的灰度采用不同的字符画出来,形成一个灰度表。于是就研究了下关于灰度值这个东西,于是跳了一个大坑。。。因为鄙人用的ubuntu,所以我的代码路径会有所不同。直接贴出原博文代码。故事的开始是这样的。。。*/

  1.关于Java实现将一张图片转成字符画(原文地址:http://blog.csdn.net/zhouli_05/article/details/7913263

    怎么样用Java实现将一张图片转成字符画??

    输入:一张图片

    输出:一个txt文档,由字符构成,看起来很像那张照片的字符画。

    基本思想:根据照片的灰度采用不同的字符画出来,形成一个灰度表。

    #首先在D盘写一个文件"temp.html",如下内容

    

 1 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 2 <html>
 3  <head>
 4   <title>图片转文本</title>
 5   <meta http-equiv="content-type" content="text/html; charset=gbk">
 6   <style type="text/css">
 7 body {
 8  font-family: 宋体; line-height: 0.8em; letter-spacing: 0px; font-size: 8px;
 9 }
10 </style>
11  </head>
12 
13  <body>
14   ${content}
15  </body>
16 </html>
View Code 

 

 

    #在D盘放一个图片(放小一点的)"a.jpg"
     #运行如下JAVA代码:

  1 import java.awt.Color;
  2 import java.awt.image.BufferedImage;
  3 import java.io.File;
  4 import java.io.FileInputStream;
  5 import java.io.FileOutputStream;
  6 import java.io.IOException;
  7 import java.io.InputStreamReader;
  8 import javax.imageio.ImageIO;
  9 
 10 public class Test {
 11 
 12  /** 此处设置灰度字符,此处只用十个字符,可以设置更多 */
 13  private static char[] cs = new char[] { '.', ',', '*', '+', '=', '&', '$', '@', '#', ' ' };
 14 
 15  public static void main(String[] args) throws IOException {
 16 
 17   // 读取图片
 18   BufferedImage bfedimage = ImageIO.read(new File("D:\\a.jpg"));
 19 
 20   // 图片转字符串后的数组
 21   char[][] css = new char[bfedimage.getWidth()][bfedimage.getHeight()];
 22 
 23   for (int x = 0; x < bfedimage.getWidth(); x++) {
 24    for (int y = 0; y < bfedimage.getHeight(); y++) {
 25     int rgb = bfedimage.getRGB(x, y);
 26     Color c = new Color(rgb);
 27     // 得到灰度值
 28     int cc = (c.getRed() + c.getGreen() + c.getBlue()) / 3;
 29     css[x][y] = cs[(int) ((cc * 10 - 1) / 255)];
 30    }
 31   }
 32 
 33   // 取得模板HTML
 34   String temp = readFile(new File("D:\\temp.html"),"gbk");
 35   StringBuffer sb = new StringBuffer();
 36 
 37   // 开始拼接内容
 38   for (int y = 0; y < css[0].length; y++) {
 39    for (int x = 0; x < css.length; x++) {
 40     sb.append(css[x][y]);
 41    }
 42    sb.append("\r\n");
 43   }
 44 
 45   System.out.println(sb.toString());
 46   // 生成文件
 47   String content = toHTML(sb.toString());
 48   String filecontent = replaceStrAllNotBack(temp, "${content}", content);
 49   writeFile(new File("D:\\content.html"), filecontent, "gbk");
 50  }
 51 
 52  public static String toHTML(String s) {
 53   s = s.replaceAll("&", "&");
 54   s = s.replaceAll(" ", " ");
 55   s = s.replaceAll(">", ">");
 56   s = s.replaceAll("<", "<");
 57   s = s.replaceAll("\"", """);
 58   s = s.replaceAll("\\\r\\\n", "<br/>");
 59   s = s.replaceAll("\\\r", "<br/>");
 60   s = s.replaceAll("\\\n", "<br/>");
 61   return s;
 62  }
 63 
 64  public static String replaceStrAllNotBack(String str, String strSrc, String strDes) {
 65   StringBuffer sb = new StringBuffer(str);
 66   int index = 0;
 67   while ((index = sb.indexOf(strSrc, index)) != -1) {
 68    sb.replace(index, index + strSrc.length(), strDes);
 69    index += strDes.length();
 70   }
 71   return sb.toString();
 72  }
 73 
 74  /**
 75   * 读文件(使用默认编码)
 76   * 
 77   * @param file
 78   * @return 文件内容
 79   * @throws IOException
 80   */
 81  public static String readFile(File file, String charset) throws IOException {
 82   InputStreamReader fr = new InputStreamReader(new FileInputStream(file), charset);
 83   StringBuffer sb = new StringBuffer();
 84   char[] bs = new char[1024];
 85   int i = 0;
 86   while ((i = fr.read(bs)) != -1) {
 87    sb.append(bs, 0, i);
 88   }
 89   fr.close();
 90   return sb.toString();
 91  }
 92 
 93  /**
 94   * 写文件
 95   * 
 96   * @param file
 97   * @param string
 98   *            字符串
 99   * @param encoding
100   *            编码
101   * @return 文件大小
102   * @throws IOException
103   */
104  public static int writeFile(File file, String string, String encoding) throws IOException {
105   FileOutputStream fos = new FileOutputStream(file);
106   try {
107    byte[] bs = string.getBytes(encoding);
108    fos.write(bs);
109    return bs.length;
110   } finally {
111    fos.close();
112   }
113  }
114 }
View Code

     #打开"D:\content.html"文件看效果吧。
  // win环境下测试了一次,发现content.html中并没有出现效果。不过效果可以在终端看见。其他补充下次博文补充。。。

  //开始入坑,发现程序是根据照片的灰度采用不同的字符画出来,形成一个灰度表,来实现画出来字符串的,然后就去科普下了一下。。。
   
   #Java实现图像灰度化(原文地址:http://liuyu314.github.io/java/2014/05/24/grayscale/)
    
几种灰度化的方法:
     1.分量法:使用RGB三个分量中的一个作为灰度图的灰度值。
      2.最值法:使用RGB三个分量中最大值或最小值作为灰度图的灰度值。 
  
      3.均值法:使用RGB三个分量的平均值作为灰度图的灰度值。

      4.加权法:由于人眼颜色敏感度不同,按下一定的权值对RGB三分量进行加权平均能得到较合理的灰度图像。一般情况按照:Y = 0.30R + 0.59G + 0.11B
      加权法实际上是取一幅图片的亮度值作为灰度值来计算,用到了YUV模型。有兴趣的同学可以研究下伽马校正)。

      一种Java实现灰度化的方法

      注:System.getProperty();java可以通过System.getProperty获得系统变量的值。一种参数的获取 你可以在程序启动时 将不变的整个程序用到的参数 使用System.setProperty("","");存起来。

      如果你搜索“Java实现灰度化”,十有八九都是一种方法(代码):

 1 public void grayImage() throws IOException{
 2     File file = new File(System.getProperty("user.dir")+"/test.jpg");
 3     BufferedImage image = ImageIO.read(file);
 4       
 5     int width = image.getWidth();  
 6     int height = image.getHeight();  
 7       
 8     BufferedImage grayImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY); 
 9     for(int i= 0 ; i < width ; i++){  
10         for(int j = 0 ; j < height; j++){  
11         int rgb = image.getRGB(i, j);  
12         grayImage.setRGB(i, j, rgb);  
13         }  
14     }  
15       
16     File newFile = new File(System.getProperty("user.dir")+"/method1.jpg");  
17     ImageIO.write(grayImage, "jpg", newFile);  
18 }
View Code

      Java实现加权法灰度化

 1 private static int colorToRGB(int alpha, int red, int green, int blue) {
 2 
 3         int newPixel = 0;
 4         newPixel += alpha;
 5         newPixel = newPixel << 8;
 6         newPixel += red;
 7         newPixel = newPixel << 8;
 8         newPixel += green;
 9         newPixel = newPixel << 8;
10         newPixel += blue;
11 
12         return newPixel;
13 
14 }
15 public static void main(String[] args) throws IOException {
16     BufferedImage bufferedImage 
17         = ImageIO.read(new File(System.getProperty("user.dir" + "/test.jpg"));
18     BufferedImage grayImage = 
19         new BufferedImage(bufferedImage.getWidth(), 
20                           bufferedImage.getHeight(), 
21                           bufferedImage.getType());
22         
23     
24     for (int i = 0; i < bufferedImage.getWidth(); i++) {
25         for (int j = 0; j < bufferedImage.getHeight(); j++) {
26             final int color = bufferedImage.getRGB(i, j);
27             final int r = (color >> 16) & 0xff;
28             final int g = (color >> 8) & 0xff;
29             final int b = color & 0xff;
30             int gray = (int) (0.3 * r + 0.59 * g + 0.11 * b);;
31             System.out.println(i + " : " + j + " " + gray);
32             int newPixel = colorToRGB(255, gray, gray, gray);
33             grayImage.setRGB(i, j, newPixel);
34         }
35     }
36     File newFile = new File(System.getProperty("user.dir") + "/ok.jpg");
37     ImageIO.write(grayImage, "jpg", newFile);
38 }
View Code

 两种方法得到的结果的差距还是很大的,我也根据原博文做了一次测试。下面贴图:       (原博文原图)



                            (Java实现灰度化的方法)
 
              
  
                             (Java实现加权法灰度化

 

posted @ 2015-12-23 22:03  奇葩的师弟  阅读(3543)  评论(0编辑  收藏  举报