当前位置: 首页 > news >正文

java实现图片转ascii字符画

2019独角兽企业重金招聘Python工程师标准>>> hot3.png

 示例图:

201318_6Sod_3568600.png

建议:图片压缩一下。

代码:

package list.test;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;  
  
import javax.imageio.ImageIO;  
  
/** 
 * @author 东哥 2016年10月27日 
 * 
 */  
public class AsciiPic {  
  
    /** 
     * @param path 
     *            图片路径 
     */  
    public static void createAsciiPic(final String path) {  
        //final String base = "\"@#&$%*o!;.";// 字符串由复杂到简单  
    	final String base = "#8XOHLTI)i=+;:,. ";// 字符串由复杂到简单  
        try {  
            final BufferedImage image = ImageIO.read(new File(path));  //读取图片
            //输出到指定文件中
            final BufferedWriter fos = new BufferedWriter(new FileWriter("D:\\\\abc.txt",false));   //true表示是否追加
            for (int y = 0; y < image.getHeight(); y += 2) {  
                for (int x = 0; x < image.getWidth(); x++) {  
                    final int pixel = image.getRGB(x, y);  
                    final int r = (pixel & 0xff0000) >> 16, g = (pixel & 0xff00) >> 8, b = pixel & 0xff;  
                    final float gray = 0.299f * r + 0.578f * g + 0.114f * b;  
                    final int index = Math.round(gray * (base.length() + 1) / 255); 
                    String s = index >= base.length() ? " " : String.valueOf(base.charAt(index));
                    System.out.print(s);
                    fos.write(s);
                }  
                fos.newLine();
                System.out.println();
            } 
            fos.close();
        } catch (final IOException e) {  
            e.printStackTrace();  
        }  
    }  
  
    /** 
     * test 
     * 
     * @param args 
     */  
    public static void main(final String[] args) {  
        AsciiPic.createAsciiPic("D:\\ABC.jpg");  
    }  
    
}  

java实现图片转ascii字符画

参考 :https://blog.csdn.net/renhd_1987/article/details/52948978

图片压缩:

package list.test;
import java.awt.Graphics2D;  
import java.awt.Rectangle;  
import java.awt.RenderingHints;  
import java.awt.geom.AffineTransform;  
import java.awt.image.BufferedImage;  
import java.awt.image.ColorModel;  
import java.awt.image.WritableRaster;  
import java.io.File;  
import java.io.FileInputStream;  
import java.io.FileNotFoundException;  
import java.io.IOException;  
import java.io.InputStream;  
  
import javax.imageio.ImageIO;  
  
/**   
 * 图片工具类,完成图片的截取 
 * 所有方法返回值均未boolean型   
 */    
public class ImageHelper {  
      /**   
     * 实现图像的等比缩放   
     * @param source   
     * @param targetW   
     * @param targetH   
     * @return   
     */    
    private static BufferedImage resize(BufferedImage source, int targetW,     
            int targetH) {     
        // targetW,targetH分别表示目标长和宽     
        int type = source.getType();     
        BufferedImage target = null;     
        double sx = (double) targetW / source.getWidth();     
        double sy = (double) targetH / source.getHeight();     
        // 这里想实现在targetW,targetH范围内实现等比缩放。如果不需要等比缩放     
        // 则将下面的if else语句注释即可     
        if (sx < sy) {     
            sx = sy;     
            targetW = (int) (sx * source.getWidth());     
        } else {     
            sy = sx;     
            targetH = (int) (sy * source.getHeight());     
        }     
        if (type == BufferedImage.TYPE_CUSTOM) { // handmade     
            ColorModel cm = source.getColorModel();     
            WritableRaster raster = cm.createCompatibleWritableRaster(targetW,     
                    targetH);     
            boolean alphaPremultiplied = cm.isAlphaPremultiplied();     
            target = new BufferedImage(cm, raster, alphaPremultiplied, null);     
        } else    
            target = new BufferedImage(targetW, targetH, type);     
        Graphics2D g = target.createGraphics();     
        // smoother than exlax:     
        g.setRenderingHint(RenderingHints.KEY_INTERPOLATION,     
                RenderingHints.VALUE_INTERPOLATION_BICUBIC);     
        g.drawRenderedImage(source, AffineTransform.getScaleInstance(sx, sy));     
        g.dispose();     
        return target;     
    }     
   
    /**   
     * 实现图像的等比缩放和缩放后的截取, 处理成功返回true, 否则返回false   
     * @param inFilePath 要截取文件的路径   
     * @param outFilePath 截取后输出的路径   
     * @param width 要截取宽度   
     * @param hight 要截取的高度   
     * @throws Exception   
     */    
    public static boolean compress(String inFilePath, String outFilePath,     
            int width, int hight) {  
        boolean ret = false;  
        File file = new File(inFilePath);  
        File saveFile = new File(outFilePath);  
        InputStream in = null;  
        try {  
            in = new FileInputStream(file);  
            ret = compress(in, saveFile, width, hight);  
        } catch (FileNotFoundException e) {  
            e.printStackTrace();  
            ret = false;  
        } finally{  
            if(null != in){  
                try {  
                    in.close();  
                } catch (IOException e) {  
                    e.printStackTrace();  
                }  
            }  
        }  
   
        return ret;  
    }   
   
    /**   
     * 实现图像的等比缩放和缩放后的截取, 处理成功返回true, 否则返回false   
     * @param in 要截取文件流 
     * @param outFilePath 截取后输出的路径   
     * @param width 要截取宽度   
     * @param hight 要截取的高度   
     * @throws Exception   
     */    
    public static boolean compress(InputStream in, File saveFile,     
            int width, int hight) {  
//     boolean ret = false;  
        BufferedImage srcImage = null;  
        try {  
            srcImage = ImageIO.read(in);  
        } catch (IOException e) {  
            e.printStackTrace();  
            return false;  
        }  
   
        if (width > 0 || hight > 0) {  
            // 原图的大小  
            int sw = srcImage.getWidth();  
            int sh = srcImage.getHeight();  
            // 如果原图像的大小小于要缩放的图像大小,直接将要缩放的图像复制过去  
            if (sw > width && sh > hight) {  
                srcImage = resize(srcImage, width, hight);  
            } else {  
                String fileName = saveFile.getName();  
                String formatName = fileName.substring(fileName  
                        .lastIndexOf('.') + 1);  
                try {  
                    ImageIO.write(srcImage, formatName, saveFile);  
                } catch (IOException e) {  
                    e.printStackTrace();  
                    return false;  
                }  
                return true;  
            }  
        }  
        // 缩放后的图像的宽和高  
        int w = srcImage.getWidth();  
        int h = srcImage.getHeight();  
        // 如果缩放后的图像和要求的图像宽度一样,就对缩放的图像的高度进行截取  
        if (w == width) {  
            // 计算X轴坐标  
            int x = 0;  
            int y = h / 2 - hight / 2;  
            try {  
                saveSubImage(srcImage, new Rectangle(x, y, width, hight), saveFile);  
            } catch (IOException e) {  
                e.printStackTrace();  
                return false;  
            }  
        }  
        // 否则如果是缩放后的图像的高度和要求的图像高度一样,就对缩放后的图像的宽度进行截取  
        else if (h == hight) {  
            // 计算X轴坐标  
            int x = w / 2 - width / 2;  
            int y = 0;  
            try {  
                saveSubImage(srcImage, new Rectangle(x, y, width, hight), saveFile);  
            } catch (IOException e) {  
                e.printStackTrace();  
                return false;                  
            }  
        }  
   
        return true;  
    }  
   
    /** 
     * 实现图像的等比缩放和缩放后的截取, 处理成功返回true, 否则返回false 
     * @param in 图片输入流 
     * @param saveFile 压缩后的图片输出流 
     * @param proportion 压缩比 
     * @throws Exception 
     */  
    public static boolean compress(InputStream in, File saveFile, int proportion) {  
        if(null == in  
                ||null == saveFile  
                ||proportion < 1){// 检查参数有效性  
            //LoggerUtil.error(ImageHelper.class, "--invalid parameter, do nothing!");  
            return false;  
        }  
   
        BufferedImage srcImage = null;  
        try {  
            srcImage = ImageIO.read(in);  
        } catch (IOException e) {  
            e.printStackTrace();  
            return false;  
        }  
        // 原图的大小  
        int width = srcImage.getWidth() / proportion;  
        int hight = srcImage.getHeight() / proportion;  
   
        srcImage = resize(srcImage, width, hight);  
   
        // 缩放后的图像的宽和高  
        int w = srcImage.getWidth();  
        int h = srcImage.getHeight();  
        // 如果缩放后的图像和要求的图像宽度一样,就对缩放的图像的高度进行截取  
        if (w == width) {  
            // 计算X轴坐标  
            int x = 0;  
            int y = h / 2 - hight / 2;  
            try {  
                saveSubImage(srcImage, new Rectangle(x, y, width, hight), saveFile);  
            } catch (IOException e) {  
                e.printStackTrace();  
                return false;  
            }  
        }  
        // 否则如果是缩放后的图像的高度和要求的图像高度一样,就对缩放后的图像的宽度进行截取  
        else if (h == hight) {  
            // 计算X轴坐标  
            int x = w / 2 - width / 2;  
            int y = 0;  
            try {  
                saveSubImage(srcImage, new Rectangle(x, y, width, hight), saveFile);  
            } catch (IOException e) {  
                e.printStackTrace();  
                return false;  
            }  
        }  
   
        return true;  
    }  
   
    /** 
     * 实现缩放后的截图 
     * @param image 缩放后的图像 
     * @param subImageBounds 要截取的子图的范围 
     * @param subImageFile 要保存的文件 
     * @throws IOException  
     */    
    private static void saveSubImage(BufferedImage image,     
            Rectangle subImageBounds, File subImageFile) throws IOException {     
        if (subImageBounds.x < 0 || subImageBounds.y < 0    
                || subImageBounds.width - subImageBounds.x > image.getWidth()     
                || subImageBounds.height - subImageBounds.y > image.getHeight()) {     
            //LoggerUtil.error(ImageHelper.class, "Bad subimage bounds");     
            return;     
        }     
        BufferedImage subImage = image.getSubimage(subImageBounds.x,subImageBounds.y, subImageBounds.width, subImageBounds.height);     
        String fileName = subImageFile.getName();     
        String formatName = fileName.substring(fileName.lastIndexOf('.') + 1);     
        ImageIO.write(subImage, formatName, subImageFile);  
    }     
      
      
   public static void main(String[] args) throws Exception {  
       /** 
        * saveSubImage 截图类的使用 
        * srcImage 为BufferedImage对象 
        * Rectangle    为需要截图的长方形坐标 
        * saveFile 需要保存的路径及名称 
        * **/  
        //需要截图的长方形坐标  
        /*Rectangle rect =new Rectangle(); 
        rect.x=40; 
        rect.y=40; 
        rect.height=160; 
        rect.width=160; 
  
        InputStream in = null; 
        //需要保存的路径及名称 
        File saveFile = new File("d:\\ioc\\files\\aaa2.jpg"); 
        //需要进行处理的图片的路径 
        in = new FileInputStream(new File("d:\\ioc\\files\\aaa.jpg")); 
        BufferedImage srcImage = null; 
        //将输入的数据转为BufferedImage对象 
        srcImage = ImageIO.read(in); 
  
        ImageHelper img=new ImageHelper(); 
        img.saveSubImage(srcImage, rect, saveFile);*/  
   
       /** 
        * compress 图片缩放类的使用(缩略图) 
        * srcImage 为InputStream对象 
        * Rectangle    为需要截图的长方形坐标 
        * proportion 为压缩比例 
        * **/  
        InputStream in = null;  
        //缩放后需要保存的路径  
        File saveFile = new File("d:\\ABC.jpg");  
        try {  
            //原图片的路径  
            in = new FileInputStream(new File("d:\\download.jpg"));  
            if(compress(in, saveFile, 5)){  
                System.out.println("图片压缩5倍!");  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        } finally {  
            in.close();  
        }  
    }  
} 

参考: https://blog.csdn.net/abubu123/article/details/77099950

转载于:https://my.oschina.net/u/3568600/blog/1826265

相关文章:

  • [CF494C]Helping People
  • oracle自带函数
  • 菜鸟要投120亿港币,在香港建超级eHub
  • 装修设计解剖书
  • BZOJ2434[Noi2011]阿狸的打字机——AC自动机+dfs序+树状数组
  • JQuery实现聊天对话框
  • 神级python程序员只需要一个公众号,再也不会错过重要资讯
  • E盘可用空间0字节,要怎样找到文件
  • jenkins详解(一)
  • C# API中的模型和它们的接口设计
  • [日常] 算法-单链表的创建-尾插法
  • 苹果发布Core ML 2
  • es6 入坑笔记(三)---数组,对象扩展
  • 从MySQL临时表谈到filesort
  • 在JPEG图片中嵌入HTML
  • [译]前端离线指南(上)
  • 【159天】尚学堂高琪Java300集视频精华笔记(128)
  • Angular 响应式表单之下拉框
  • AWS实战 - 利用IAM对S3做访问控制
  • C++入门教程(10):for 语句
  • git 常用命令
  • iOS高仿微信项目、阴影圆角渐变色效果、卡片动画、波浪动画、路由框架等源码...
  • node入门
  • SpiderData 2019年2月25日 DApp数据排行榜
  • vue-router的history模式发布配置
  • vue数据传递--我有特殊的实现技巧
  • 阿里云爬虫风险管理产品商业化,为云端流量保驾护航
  • 从零开始在ubuntu上搭建node开发环境
  • 从重复到重用
  • 技术攻略】php设计模式(一):简介及创建型模式
  • 码农张的Bug人生 - 见面之礼
  • 七牛云假注销小指南
  • 时间复杂度与空间复杂度分析
  • 完善智慧办公建设,小熊U租获京东数千万元A+轮融资 ...
  • ​io --- 处理流的核心工具​
  • ​比特币大跌的 2 个原因
  • #我与Java虚拟机的故事#连载09:面试大厂逃不过的JVM
  • (1)安装hadoop之虚拟机准备(配置IP与主机名)
  • (Matalb时序预测)WOA-BP鲸鱼算法优化BP神经网络的多维时序回归预测
  • (Redis使用系列) Springboot 使用redis实现接口Api限流 十
  • (附源码)spring boot网络空间安全实验教学示范中心网站 毕业设计 111454
  • (附源码)ssm高校社团管理系统 毕业设计 234162
  • (免费领源码)python+django+mysql线上兼职平台系统83320-计算机毕业设计项目选题推荐
  • (四)JPA - JQPL 实现增删改查
  • (原創) 是否该学PetShop将Model和BLL分开? (.NET) (N-Tier) (PetShop) (OO)
  • (转)母版页和相对路径
  • (转)自己动手搭建Nginx+memcache+xdebug+php运行环境绿色版 For windows版
  • (最全解法)输入一个整数,输出该数二进制表示中1的个数。
  • .bat批处理(八):各种形式的变量%0、%i、%%i、var、%var%、!var!的含义和区别
  • .NET Core日志内容详解,详解不同日志级别的区别和有关日志记录的实用工具和第三方库详解与示例
  • .Net Core与存储过程(一)
  • .NET Framework .NET Core与 .NET 的区别
  • .net 逐行读取大文本文件_如何使用 Java 灵活读取 Excel 内容 ?
  • :“Failed to access IIS metabase”解决方法
  • @Transactional 竟也能解决分布式事务?