使用Java代码将一张图片生成为字符画

java

 测试的图片:

 输出的结果:

代码:

 1 package test;

2

3 import java.awt.image.BufferedImage;

4 import java.io.File;

5 import java.io.IOException;

6

7 import javax.imageio.ImageIO;

8

9 /**

10 * 将一张图片生成为字符画

11 *

12 * @author 11475

13 *

14 */

15 public class DemoCase {

16 /**

17 * @param path 图片路径

18 */

19 public static void createAsciiPic(final String path) {

20 final String base = "@#&$%*o!;.";// 字符串由复杂到简单

21 try {

22 final BufferedImage image = ImageIO.read(new File(path));

23 for (int y = 0; y < image.getHeight(); y += 2) {

24 for (int x = 0; x < image.getWidth(); x++) {

25 final int pixel = image.getRGB(x, y);

26 final int r = (pixel & 0xff0000) >> 16, g = (pixel & 0xff00) >> 8, b = pixel & 0xff;

27 final float gray = 0.299f * r + 0.578f * g + 0.114f * b;

28 final int index = Math.round(gray * (base.length() + 1) / 255);

29 System.out.print(index >= base.length() ? " " : String.valueOf(base.charAt(index)));

30 }

31 System.out.println();

32 }

33 } catch (final IOException e) {

34 e.printStackTrace();

35 }

36 }

37

38 /**

39 * 在 createAsciiPic(final String path)添加图片的路径

40 */

41 public static void main(final String[] args) {

42 DemoCase.createAsciiPic("C:\\Users\\11475\\Desktop\\resizeApi (2).png");

43 }

44 }

以上是 使用Java代码将一张图片生成为字符画 的全部内容, 来源链接: utcz.com/z/392778.html

回到顶部