圖片相關處理

1 按比例縮放圖片

private Bitmap zoomImg(Bitmap bm, int newWidth, int newHeight) {
        // 獲得圖片的寬高
        int width = bm.getWidth();
        int height = bm.getHeight();
        // 計算縮放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要縮放的matrix參數
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的圖片
        Bitmap newbm = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, true);
        return newbm;
    }

2 文件生成位圖

/**
     * 將文件生成位圖
     * @param path
     * @return
     * @throws IOException
     */
    public BitmapDrawable getImageDrawable(String path)
            throws IOException
    {
        //打開文件
        File file = new File(path);
        if(!file.exists())
        {
            return null;
        }

        ByteArrayOutputStream outStream = new ByteArrayOutputStream();
        byte[] bt = new byte[2048];

        //得到文件的輸入流
        InputStream in = new FileInputStream(file);

        //將文件讀出到輸出流中
        int readLength = in.read(bt);
        while (readLength != -1) {
            outStream.write(bt, 0, readLength);
            readLength = in.read(bt);
        }

        //轉換成byte 後 再格式化成位圖
        byte[] data = outStream.toByteArray();
        Bitmap bitmap = BitmapFactory.decodeByteArray(data, 0, data.length);// 生成位圖
        BitmapDrawable bd = new BitmapDrawable(bitmap);

        return bd;
    }

3 Bitmap轉文件

//方式一
File file=new File(“/storage/emulated/0/1234.jpg”);//將要保存圖片的路徑 
  try { 
          BufferedOutputStream bos = new BufferedOutputStream(new     FileOutputStream(file)); 
          bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bos); 
          bos.flush(); 
          bos.close(); 
    } catch (IOException e) { 
        e.printStackTrace(); 
    } 
}

//方式二
try{
String filePath=”/storage/emulated/0/123.jpg"; 
Bitmap bitmap=BitmapFactory.decodeFile(filePath,getBitmapOption(2)); //將圖片的長和寬縮小味原來的1/2
}catch(Exception e){
e.printStackTrace();
}

private Options getBitmapOption(int inSampleSize){ 
System.gc(); 
BitmapFactory.Options options = new BitmapFactory.Options(); 
options.inPurgeable = true; 
options.inSampleSize = inSampleSize; 
return options; 
}

4 圖片url轉drawable

 /**
     * 圖片url轉drawable
     * @param url url
     * @param callBack 轉換後回調
     */
    public static void getDrawableFromUrl(final String url, final ImageCallBack callBack)
    {
        ThreadUtils.runOnSubThread(new Runnable()
        {
            @Override
            public void run()
            {
                try
                {
                    is = (InputStream) new URL(url).getContent();
                    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
                    int len = -1;
                    byte[] buffer = new byte[1024];
                    while ((len = is.read(buffer)) != -1)
                    {
                        outStream.write(buffer, 0, len);
                    }
                    byte[] imgBuffer = outStream.toByteArray();
                    outStream.close();
                    is.close();
                    is = new ByteArrayInputStream(imgBuffer);
                    Drawable drawable = Drawable.createFromStream(is, "src");
                    callBack.onSuccess(drawable);
                    is.close();
                } catch (IOException e)
                {
                    callBack.onSuccess(null);
                    e.printStackTrace();
                }

            }
        });
    }
    
    
    public interface ImageCallBack
    {
        void onSuccess(Object o);
    }

5 獲取bitmap寬高

public static void getBitmapFromUrl(String path,IBitmap iBitmap) {
        ThreadHelper.runOnSubThread(() -> {
            try {
                URL url = new URL(path);
                HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                conn.setConnectTimeout(5000);
                conn.setRequestMethod("GET");
                if (conn.getResponseCode() == 200) {
                    InputStream inputStream = conn.getInputStream();
                    Bitmap bgBitmap = BitmapFactory.decodeStream(inputStream);
                    iBitmap.getWidthAndHeight(bgBitmap.getWidth(),bgBitmap.getHeight());
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
    }

public interface IBitmap {
    /*
     * 獲取bitmap的寬高
     * @author fflin
     * 2019/3/22  12:02
     */
    void getWidthAndHeight(int width, int height);
}

6 通過流加載本地圖片

String path = "/storage/emulated/0/Pictures/Screenshots/Screenshot_2016" +
                    "-07-15-11-13-45.png";
            Bitmap loacalBitmap = getLoacalBitmap(path);

7 加載本地圖片

/**
     * 加載本地圖片
     *
     * @param url
     * @return
     */
    public Bitmap getLoacalBitmap(String url) {
        try {
            FileInputStream fis = new FileInputStream(url);
            return BitmapFactory.decodeStream(fis);  ///把流轉化爲Bitmap圖片

        } catch (FileNotFoundException e) {
            e.printStackTrace();
            L.e("ChatFrame", "加載本地圖片的異常:" + e.getMessage());
            return null;
        }
    }

8 圖片壓縮

    private ByteArrayOutputStream getByteArrayOutputStream(Bitmap bitmap) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);//質量壓縮方法,這裏100表示不壓縮,把壓縮後的數據存放到baos中
        int options = 100;
        while (baos.toByteArray().length / 1024 > 100) {  //循環判斷如果壓縮後圖片是否大於100kb,大於繼續壓縮
            baos.reset();//重置baos即清空baos
            bitmap.compress(Bitmap.CompressFormat.JPEG, options, baos);//這裏壓縮options%,把壓縮後的數據存放到baos中
            options -= 10;//每次都減少10
        }
        return baos;
    }

9 byte轉bitmap

public Bitmap getBitmapFromByte(byte[] temp) {
        if (temp != null) {
            Bitmap bitmap = BitmapFactory.decodeByteArray(temp, 0, temp.length);
            return bitmap;
        } else {
            return null;
        }
    }

10 url轉bitmap

/**
    * 從服務器取圖片
    * @param url
    * @return
    */
    public static Bitmap getHttpBitmap(String url) {
         URL myFileUrl = null;
         Bitmap bitmap = null;
         try {
              myFileUrl = new URL(url);
         } catch (MalformedURLException e) {
              e.printStackTrace();
         }
         try {
              HttpURLConnection conn = (HttpURLConnection) myFileUrl.openConnection();
              conn.setConnectTimeout(0);
              conn.setDoInput(true);
              conn.connect();
              InputStream is = conn.getInputStream();
              bitmap = BitmapFactory.decodeStream(is);
              is.close();
         } catch (IOException e) {
              e.printStackTrace();
         }
         return bitmap;
    }

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章