Android圖片處理——壓縮、剪裁、圓角、儲存

來源:互聯網
上載者:User

標籤:圖片處理   android   

項目中用到的關於圖片的處理

public class UtilPicture {    public static final String IMAGE_UNSPECIFIED = "image/*";    /**     * 將圖片儲存至SD卡,需判斷是否裝有SD卡、是否可讀寫、是否有空間,否則提示出錯     * @param ctx 上下文     * @param jpeg 要儲存的照片     * @param quality 壓縮照片的品質,0至100,100最佳,一般80-90     * @param filePath 儲存的路徑     * @param filename 照片的名稱     * @return     */    public static boolean save_picture(Context ctx, Bitmap bitmap, int quality, String filePath, String filename) {        ByteArrayOutputStream baos = new ByteArrayOutputStream();        bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);        byte[] data = baos.toByteArray();        if (!Common.checkSDStatus(data.length/1024/1024)) {            Toast.makeText(ctx, "您的儲存卡有錯誤", Toast.LENGTH_SHORT).show();            return false;        }        try {            File destDir = new File(filePath);            if (!destDir.exists())                destDir.mkdirs();            String path = filePath + "/" + filename;            File file = new File(path);            if (!file.exists())                file.createNewFile();            FileOutputStream fos = new FileOutputStream(file);            fos.write(data);            fos.close();        } catch (Exception e) {            e.printStackTrace();            return false;        }        return true;    }    /**     * 獲得圓角圖片的方法     * @param bitmap 需處理的圖片     * @param roundPx 圓角的弧率     * @return     */    public static Bitmap getRoundedCornerBitmap(Bitmap bitmap, float roundPx) {        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);        Canvas canvas = new Canvas(output);        final int color = 0xff424242;        final Paint paint = new Paint();        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());        final RectF rectF = new RectF(rect);        paint.setAntiAlias(true);        canvas.drawARGB(0, 0, 0, 0);        paint.setColor(color);        canvas.drawRoundRect(rectF, roundPx, roundPx, paint);        paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));        canvas.drawBitmap(bitmap, rect, rect, paint);        return output;    }    /**     * 圖片中繪入GPS和時間等文字     * @param bitmap 需處理的圖片     * @param datetime 時間     * @param lat 經度     * @param lng 緯度     * @return     */    public static Bitmap getGpsBitmap(Bitmap bitmap, String datetime, String lat, String lng) {        Bitmap output = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Config.ARGB_8888);        /* 把位元影像寫進畫布canvas類 */        Canvas canvas = new Canvas(output);        /* 畫布的地區 */        final Rect rect = new Rect(0, 0, bitmap.getWidth(), bitmap.getHeight());        /* 噴漆Paint類 */        Paint paint = new Paint();        paint.setAntiAlias(true);//消除鋸齒        paint.setColor(Color.RED);//著色        paint.setTextSize(16);//字型大小        canvas.drawText("經度:" + lng, 10, 20, paint);        canvas.drawText("緯度:" + lat, 10, 38, paint);        canvas.drawText("時間:" + datetime, 10, 56, paint);        paint.setXfermode(new PorterDuffXfermode(Mode.DST_ATOP));        canvas.drawBitmap(bitmap, rect, rect, paint);        return output;    }    /**     * 裁切圖片     * @param originFile 源檔案     * @param TargetFile 目標檔案     * @param aspect 寬高比例,如果為null,則不限制     * @param output 輸出解析度     * @return     */    public static Intent startPhotoZoom(File originFile, File TargetFile, int[] aspect, int[] output) {        Intent intent = new Intent("com.android.camera.action.CROP");        intent.setDataAndType(Uri.fromFile(originFile), IMAGE_UNSPECIFIED);        intent.putExtra("crop", "true");        intent.putExtra("noFaceDetection", true);        intent.putExtra("return-data", false);        if (null != output) {            BitmapFactory.Options op = new BitmapFactory.Options();            op.inJustDecodeBounds = true;            BitmapFactory.decodeFile(originFile.getPath(), op);            int jpgWidth = op.outWidth;            int jpgHeight = op.outHeight;            if (jpgWidth > output[0] && jpgHeight > output[1]) {                intent.putExtra("outputX", output[0]);                intent.putExtra("outputY", output[1]);            }        }        if (null != aspect) {            intent.putExtra("aspectX", aspect[0]);            intent.putExtra("aspectY", aspect[1]);        }        if (!TargetFile.exists())            try {                TargetFile.createNewFile();            } catch (IOException e) {                e.printStackTrace();            }        intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(TargetFile));        intent.putExtra("outputFormat", Bitmap.CompressFormat.JPEG.toString());        return intent;    }    /**     * 從相簿中選擇一張照片之後,擷取該照片的絕對路徑     * @param ctx     * @param photoUri     * @return     */    public static String getPickPhotoPath(Context ctx, Uri photoUri) {        Cursor cursor = null;        try {            cursor = ctx.getContentResolver().query(photoUri, null, null, null, null);            cursor.moveToFirst();            String imgPath = cursor.getString(cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA));            return imgPath;        } catch (Exception e) {            return "";        } finally {            cursor.close();        }    }    public static File getPickPhotoFile(Context ctx, Uri photoUri) {        String imgPath = getPickPhotoPath(ctx, photoUri);        if (!TextUtils.isEmpty(imgPath))            return new File(imgPath);        else            return null;    }    /**     * 壓縮圖片大小,避免圖片過大,保持比例不變,寬或高不超過XX個像素     * @param newName 新的檔案名稱     * @param filePath 原檔案全路徑,包含檔案名稱     * @param attachPath 處理過後,檔案存放的位置     * @param String 新的檔案全路徑     */    public static String compressPixelPhotos(final Context ctx, final String newName, final String filePath,            final String attachPath) {        BitmapFactory.Options op = new BitmapFactory.Options();        op.inJustDecodeBounds = true;        BitmapFactory.decodeFile(filePath, op);        int jpgWidth = op.outWidth;        int jpgHeight = op.outHeight;        if (jpgWidth > 800 || jpgHeight > 800) {            int wSendRatio = (int) Math.ceil(jpgWidth / 800.0f);            int hSendRatio = (int) Math.ceil(jpgHeight / 800.0f);            if (wSendRatio > 1 && hSendRatio > 1) {                op.inSampleSize = wSendRatio > hSendRatio ? wSendRatio : hSendRatio;            }            op.inJustDecodeBounds = false;            Bitmap b = BitmapFactory.decodeFile(filePath, op);            if (!save_picture(ctx, b, 90, attachPath, newName)) {                Common.copyFileToFile(filePath, attachPath + File.separator + newName);            }            if (b != null && !b.isRecycled())                b.recycle();        } else {            Common.copyFileToFile(filePath, attachPath + File.separator + newName);        }        return attachPath + File.separator + newName;    }    /**     * 檢查圖片解析度大小,是否需要壓縮     * @param ctx     * @param filePath     * @return     */    public static boolean compressPixelPhotosCheck(final Context ctx, final String filePath) {        BitmapFactory.Options op = new BitmapFactory.Options();        op.inJustDecodeBounds = true;        BitmapFactory.decodeFile(filePath, op);        if (op.outWidth > 800 || op.outHeight > 800) {            return true;        } else {            return false;        }    }    /**     * 將     * @param filename 檔案名稱,全路徑     * @param jpgGetWidth 照片寬     * @param jpgGetHeight 照片高     * @return     */    public static Bitmap decodeFile(String filename, int jpgGetWidth, int jpgGetHeight) {        Bitmap b = null;        try {            BitmapFactory.Options op = new BitmapFactory.Options();            op.inJustDecodeBounds = true;            BitmapFactory.decodeFile(filename, op);            int jpgWidth = op.outWidth;            int jpgHeight = op.outHeight;            int wSendRatio = (int) Math.ceil(jpgWidth / Double.valueOf(jpgGetWidth));            int hSendRatio = (int) Math.ceil(jpgHeight / Double.valueOf(jpgGetHeight));            if (wSendRatio > 1 && hSendRatio > 1) {                op.inSampleSize = wSendRatio > hSendRatio ? wSendRatio : hSendRatio;            }            op.inJustDecodeBounds = false;            b = BitmapFactory.decodeFile(filename, op);        } catch (Exception e) {        }        return b;    }}

更多交流可加技術討論群:71262831
掃一掃,一起坐看風雲變幻。掃描下方二維碼關注it達人(也可搜尋:it達人)。
為您推送最新開發資源、分享it牛人職業發展經驗:

Android圖片處理——壓縮、剪裁、圓角、儲存

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.