java實現圖片轉ascii字符畫

 示例圖:java

建議:圖片壓縮一下。工具

代碼:.net

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字符畫code

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

圖片壓縮:對象

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/77099950blog

相關文章
相關標籤/搜索