圖片改變像素,寬高,Base64編碼處理

1.改變圖片像素

private void setAlpha(String os) {
        /**
         * 增長測試項
         * 讀取圖片,繪製成半透明,修改像素
         */
        try {
          ImageIcon imageIcon = new ImageIcon(os);
          BufferedImage bufferedImage = new BufferedImage(imageIcon.getIconWidth(),imageIcon.getIconHeight()
              , BufferedImage.TYPE_USHORT_565_RGB);
          Graphics2D g2D = (Graphics2D) bufferedImage.getGraphics();
          g2D.drawImage(imageIcon.getImage(), 0, 0,
                               imageIcon.getImageObserver());
          //循環每個像素點,改變像素點的Alpha值
          int alpha = 100;
          System.out.println(System.currentTimeMillis());
          
          for (int j1 = bufferedImage.getMinY(); j1 < bufferedImage.getHeight(); j1++) {
            for (int j2 = bufferedImage.getMinX(); j2 < bufferedImage.getWidth(); j2++) {
              int pixel = bufferedImage.getRGB(j2, j1);
              int[]   rgb = new int[3];
              rgb[0] = (pixel & 0xff0000) >> 16;
              rgb[1] = (pixel & 0xff00) >> 8;
              rgb[2] = (pixel & 0xff);

              pixel = ( (alpha + 1) << 24) | (pixel & 0x00ffffff);
              bufferedImage.setRGB(j2, j1, pixel);
            }
          }
          System.out.println(System.currentTimeMillis());
          g2D.drawImage(bufferedImage, 0, 0, imageIcon.getImageObserver());

          //生成圖片爲PNG
          ImageIO.write(bufferedImage, "jpg",  new File("C:\\Desktop\\1.jpg"));
        }
        catch (Exception e) {
          e.printStackTrace();
        }
      }

2.改變圖片寬高

/**
     * 按指定高度 等比例縮放圖片
     * 
     * @param imageFile
     * @param newPath
     * @param newWidth 新圖的寬度
     * @throws IOException
     */
    public static void zoomImageScale(File imageFile, String newPath, int newWidth) throws IOException {
    	System.out.println("------------------------------------------------------------------");
         if(!imageFile.canRead())
             return;
        BufferedImage bufferedImage = ImageIO.read(imageFile);
        if (null == bufferedImage) 
            return;
        
        int originalWidth = bufferedImage.getWidth();
        int originalHeight = bufferedImage.getHeight();
        double scale = (double)originalWidth / (double)newWidth;    // 縮放的比例
        
        int newHeight =  (int)(originalHeight / scale);

        zoomImageUtils(imageFile, newPath, bufferedImage, newWidth, newHeight);
    }
    private static void zoomImageUtils(File imageFile, String newPath, BufferedImage bufferedImage, int width, int height)
            throws IOException{
       
         String suffix = StringUtils.substringAfterLast(imageFile.getName(), ".");
        
         // 處理 png 背景變黑的問題
        if(suffix != null && (suffix.trim().toLowerCase().endsWith("png") || suffix.trim().toLowerCase().endsWith("gif"))){
        	
            BufferedImage to= new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB); 
            Graphics2D g2d = to.createGraphics(); 
            to = g2d.getDeviceConfiguration().createCompatibleImage(width, height, Transparency.TRANSLUCENT); 
            g2d.dispose(); 
            
            g2d = to.createGraphics(); 
            System.out.println(width+"---"+height+"------------------------------------------------------------------"+Image.SCALE_AREA_AVERAGING);
            Image from = bufferedImage.getScaledInstance(width, height, Image.SCALE_AREA_AVERAGING); 
            g2d.drawImage(from, 0, 0, null);
            g2d.dispose(); 
            
            ImageIO.write(to, suffix, new File(newPath));
        }else{
        	 System.out.println("------------------------------------------------------------------");
            // 高質量壓縮,其實對清晰度而言沒有太多的幫助
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            tag.getGraphics().drawImage(bufferedImage, 0, 0, width, height, null);

            FileOutputStream out = new FileOutputStream(newPath);    // 將圖片寫入 newPath
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
            JPEGEncodeParam jep = JPEGCodec.getDefaultJPEGEncodeParam(tag);
            jep.setQuality(1f, true);    //壓縮質量, 1 是最高值
            encoder.encode(tag, jep);
            out.close();
            
            BufferedImage newImage = new BufferedImage(width, height, bufferedImage.getType());
            
            Graphics g = newImage.getGraphics();
            g.drawImage(bufferedImage, 0, 0, width, height, null);
            g.dispose();
            ImageIO.write(newImage, suffix, new File(newPath));
        }
    }

3.將圖片文件轉化爲字節數組字符串,並對其進行Base64編碼處理

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import java.io.*;

/**
 * @author hhr
 * @create 2017-09-08
 **/
public class Base64Test {
    public static void main(String[] args) {
        String strImg = GetImageStr();
        System.out.println(strImg);
        GenerateImage(strImg);
    }

    //圖片轉化成base64字符串
    public static String GetImageStr() {//將圖片文件轉化爲字節數組字符串,並對其進行Base64編碼處理
        String imgFile = "C:\\Users\\Administrator\\Desktop\\1.png";//待處理的圖片
        InputStream in = null;
        byte[] data = null;
        //讀取圖片字節數組
        try {
            in = new FileInputStream(imgFile);
            data = new byte[in.available()];
            in.read(data);
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        //對字節數組Base64編碼
        BASE64Encoder encoder = new BASE64Encoder();
        return encoder.encode(data);//返回Base64編碼過的字節數組字符串
    }

    //base64字符串轉化成圖片
    public static boolean GenerateImage(String imgStr) {   //對字節數組字符串進行Base64解碼並生成圖片
        if (imgStr == null) //圖像數據爲空
            return false;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解碼
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {//調整異常數據
                    b[i] += 256;
                }
            }
            //生成jpeg圖片
            String imgFilePath = "C://222.jpg";//新生成的圖片
            OutputStream out = new FileOutputStream(imgFilePath);
            out.write(b);
            out.flush();
            out.close();
            return true;
        } catch (Exception e) {
            return false;
        }
    }
相關文章
相關標籤/搜索