base64轉byte[]、byte[]轉base6四、byte[]轉圖片後圖片按固定寬高縮放

/**
     * 圖片縮放
     */
    public static BufferedImage ImageStringByte(int width, byte[] b) {
        
        InputStream buffin = new ByteArrayInputStream(b);
        BufferedImage src = null;
        try {
            src = ImageIO.read(buffin);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } // 讀入文件
        int widthYuan = src.getWidth(); // 獲得源圖寬
        int heightYuan = src.getHeight(); // 獲得源圖長
        heightYuan = heightYuan / (widthYuan/width);
        widthYuan = width ;
        Image image = src.getScaledInstance(widthYuan, heightYuan, Image.SCALE_DEFAULT);
        BufferedImage tag = new BufferedImage(widthYuan, heightYuan, BufferedImage.TYPE_INT_RGB);
        Graphics g = tag.getGraphics();
        boolean drawImage = g.drawImage(image, 0, 0, null); // 繪製縮小後的圖
        g.dispose();
       return tag;// 輸出到文件流
    }html

 

/**
     * byte流轉爲字符串
     */
    public static String stringsByImage(byte[] binaryData) {
        String b = null;
        try {
            // b = decoder.decodeBuffer(base64str);
            b = Base64.encode(binaryData);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return b;
    }java

    /**
     * 將圖片字符串流轉爲圖片二進制
     */
    public static byte[] ImageByString(String base64str) {
        byte[] b = null;
        try {
            b = Base64.decode(base64str);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return b;
    }code

/**
     * 將圖片直接轉爲byte
     */
    public static byte[] byteByImage(BufferedImage  image) {
        ByteArrayOutputStream bos = new ByteArrayOutputStream(); // 將圖片轉爲byte
        try {
            ImageIO.write(image, "jpg", bos);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return bos.toByteArray();

    }htm

原文出處:https://www.cnblogs.com/han-java/p/10502448.htmlblog

相關文章
相關標籤/搜索