直播app開發搭建,Android studio 圖片壓縮

zhibo系統開發發表於2023-09-27

直播app開發搭建,Android studio 圖片壓縮

獲取圖片目錄

File file=Environment.getExternalStorageDirectory();//獲取根路徑 storage/emulated/0
String path1=file.getPath()+"/Pictures/1655215651628.jpg";//Pictures資料夾下面的 1655215651628.jpg圖片名


     //path 壓縮圖片的路徑
        String path="/storage/emulated/0/Pictures/1655215651628.jpg";
        Bitmap bitmap = obtainImageFromPath(path, 100, 160);
        saveBitmapFile(bitmap);//把壓縮圖片儲存
        image.setImageBitmap(bitmap);
 //傳入路徑和寬高
    public static Bitmap obtainImageFromPath(String path, int width, int height) {
        BitmapFactory.Options o = new BitmapFactory.Options();
        o.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(path, o);
        o.inSampleSize = calculateSampleSize(o, width, height);
        o.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(path, o);
    }
    //計算樣本量
    private static int calculateSampleSize(BitmapFactory.Options o, int reqWidth, int reqHeight) {
        int sampleSize = 1;
        if (o.outWidth > reqWidth || o.outHeight > reqHeight) {
            final int halfWidth = o.outWidth / 2;
            final int halfHeight = o.outHeight / 2;
            while ((halfHeight / sampleSize) >= reqHeight
                    && (halfWidth / sampleSize) >= reqWidth) {
                sampleSize *= 2;
            }
        }
        return sampleSize;
    }
//儲存壓縮的檔案
    public void saveBitmapFile(Bitmap bitmap){
        File file=new File("/storage/emulated/0/Pictures/1655215651628.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();
        }
    }

 以上就是 直播app開發搭建,Android studio 圖片壓縮,更多內容歡迎關注之後的文章


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/69978258/viewspace-2986294/,如需轉載,請註明出處,否則將追究法律責任。

相關文章