如何无失真调整Bitmap尺寸至不超过720*1280并保持比例?
Hey there! I’ve run into the exact same bitmap resizing headache before—nothing’s more frustrating than losing image quality when you’re trying to fit a bitmap into specific dimensions. Let’s fix this with a solution that keeps your image crisp, maintains aspect ratio, and respects the 720x1280 limit (with optional blank canvas if needed).
Core Approach
The main goals here are:
- Preserve aspect ratio: No stretching or squishing the original image
- High-quality scaling: Use anti-aliasing and filtering to avoid pixelation
- Respect 720x1280 limit: If the scaled image is smaller than this, center it on a blank canvas instead of stretching
Step-by-Step Implementation (Android Example)
Let’s break this down into reusable code blocks that you can adapt to your project.
1. Calculate the Correct Scale Factor
First, we need to figure out how much to scale the image so it fits within 720x1280 without distortion. We’ll take the smaller of the two possible scale ratios (width vs height) to ensure neither dimension exceeds the limit.
private float calculateScaleFactor(int originalWidth, int originalHeight, int maxWidth, int maxHeight) { // Calculate scale for width and height separately float widthScale = (float) maxWidth / originalWidth; float heightScale = (float) maxHeight / originalHeight; // Use the smaller scale to keep the image within bounds return Math.min(widthScale, heightScale); }
2. Create a High-Quality Scaled Bitmap
Instead of using the basic Bitmap.createScaledBitmap() (which can cause pixelation), we’ll use a Canvas with an optimized Paint object to ensure smooth scaling.
private Bitmap getScaledBitmap(Bitmap originalBitmap, float scaleFactor) { int scaledWidth = Math.round(originalBitmap.getWidth() * scaleFactor); int scaledHeight = Math.round(originalBitmap.getHeight() * scaleFactor); // Create a new bitmap with the same color configuration as the original Bitmap scaledBitmap = Bitmap.createBitmap(scaledWidth, scaledHeight, originalBitmap.getConfig()); Canvas canvas = new Canvas(scaledBitmap); // Configure paint for maximum quality Paint paint = new Paint(); paint.setAntiAlias(true); // Smooth edges paint.setFilterBitmap(true); // Reduce pixelation during scaling paint.setDither(true); // Improve color accuracy // Draw the original bitmap onto the scaled canvas Rect srcRect = new Rect(0, 0, originalBitmap.getWidth(), originalBitmap.getHeight()); Rect dstRect = new Rect(0, 0, scaledWidth, scaledHeight); canvas.drawBitmap(originalBitmap, srcRect, dstRect, paint); return scaledBitmap; }
3. Add Optional Blank Canvas (If Needed)
If the scaled image is smaller than 720x1280, we’ll center it on a blank canvas of the target size. This keeps the image intact while meeting the dimension requirement.
private Bitmap createFinalBitmap(Bitmap scaledBitmap) { int targetWidth = 720; int targetHeight = 1280; // Create the blank canvas bitmap Bitmap finalBitmap = Bitmap.createBitmap(targetWidth, targetHeight, scaledBitmap.getConfig()); Canvas canvas = new Canvas(finalBitmap); // Fill the background (use Color.TRANSPARENT for a clear background) canvas.drawColor(Color.WHITE); // Calculate position to center the scaled image int leftOffset = (targetWidth - scaledBitmap.getWidth()) / 2; int topOffset = (targetHeight - scaledBitmap.getHeight()) / 2; // Draw the scaled image onto the blank canvas canvas.drawBitmap(scaledBitmap, leftOffset, topOffset, null); return finalBitmap; }
4. Put It All Together
Here’s how to use these methods in your code:
// Your original bitmap (replace with your actual bitmap) Bitmap originalBitmap = BitmapFactory.decodeResource(getResources(), R.drawable.your_image); // Calculate the scale factor float scaleFactor = calculateScaleFactor(originalBitmap.getWidth(), originalBitmap.getHeight(), 720, 1280); // Get the high-quality scaled bitmap Bitmap scaledBitmap = getScaledBitmap(originalBitmap, scaleFactor); // Create the final bitmap (with blank canvas if needed) Bitmap finalBitmap = createFinalBitmap(scaledBitmap); // Clean up to avoid memory leaks originalBitmap.recycle(); scaledBitmap.recycle();
Key Notes to Avoid Distortion
- Always use the original bitmap’s color config: This prevents unexpected color shifts or quality loss.
- Don’t skip paint optimizations: The
antiAlias,filterBitmap, andditherflags are critical for smooth, crisp scaling. - Handle memory carefully: Recycle bitmaps you no longer need to prevent out-of-memory errors, especially with large images.
- Adjust background color: If you need a transparent background, replace
Color.WHITEwithColor.TRANSPARENTin thecreateFinalBitmapmethod.
内容的提问来源于stack exchange,提问作者Dinesh Neupane

