Android会将图像的任何尺寸调整为特定尺寸,并将所有图像保存到sdcard文件夹

时间:2015-07-26 19:23:14

标签: android image resize image-resizing

让我说我的SD卡中有一些图像,但它们有不同的尺寸,如1920 * 1080,2500 * 1400,600 * 400等。

现在我想将所有这些尺寸调整到特定尺寸(820 * 480)而不会降低质量并保持纵横比。调整大小/向上调整后,我想用黑色填充所需尺寸的空白区域。

怎么做?

1 个答案:

答案 0 :(得分:0)

    Bitmap bFrom = BitmapFactory.decodeFile("filename");
    final int w = bFrom.getWidth();
    final int h = bFrom.getHeight();
    final int destW = 820;
    final int destH = 480;

    if ((w > 0) && (h > 0)) {
        Bitmap bTo = Bitmap.createBitmap(destW, destH, bFrom.getConfig());
        Canvas canvas = new Canvas(bTo); // Canvas to draw
        canvas.drawColor(Color.BLACK); // Clear the canvas
        float scale = Math.min((float) destW / w, (float) destH / h); // calculate the scale
        float scaledW = w * scale;
        float scaledH = h * scale;
        RectF destRect = new RectF((destW - scaledW) * 0.5f, (destH - scaledH) * 0.5f, (destW + scaledW) * 0.5f, (destH + scaledH) * 0.5f);
        canvas.drawBitmap(bFrom, null, destRect, null); // draw with scale;
        try {
            FileOutputStream fos = new FileOutputStream("output_filename");
            try {
                bTo.compress(Bitmap.CompressFormat.PNG, 100, fos); // save to file as png (lossless)
            } finally {
                bTo.close();
            }
        } catch (IOException ioe) {
            // handle IOException 
        }
    }