java - 在android中缩小图像并使其成为正方形

标签 java android bitmap

我需要一种将图像缩小到 78x78 的方法。我找到了通过剪切部分图像来实现此目的的方法,如下所示:

    Bitmap image = Bitmap.createBitmap(image, 0, 0, 78, 78);

但我需要尽可能多地保留图像。我曾想过缩小图像,然后使其成为正方形:

    Bitmap image = Bitmap.createScaledBitmap(imageTest, 78, 78, true);

但是这当然会创建一个被压扁的方形图像。

谁能建议我如何创建一个不重新缩放并尽可能保留原始图像的 78x78 图像?

最佳答案

据我了解,您应该缩小图像并居中裁剪图像。试试这个代码。

public Bitmap scaleCenterCrop(Bitmap source, int newHeight, int newWidth) {
int sourceWidth = source.getWidth();
int sourceHeight = source.getHeight();

// Compute the scaling factors to fit the new height and width, respectively.
// To cover the final image, the final scaling will be the bigger 
// of these two.
float xScale = (float) newWidth / sourceWidth;
float yScale = (float) newHeight / sourceHeight;
float scale = Math.max(xScale, yScale);

// Now get the size of the source bitmap when scaled
float scaledWidth = scale * sourceWidth;
float scaledHeight = scale * sourceHeight;

// Let's find out the upper left coordinates if the scaled bitmap
// should be centered in the new size give by the parameters
float left = (newWidth - scaledWidth) / 2;
float top = (newHeight - scaledHeight) / 2;

// The target rectangle for the new, scaled version of the source bitmap will now
// be
RectF targetRect = new RectF(left, top, left + scaledWidth, top + scaledHeight);

// Finally, we create a new bitmap of the specified size and draw our new,
// scaled bitmap onto it.
Bitmap dest = Bitmap.createBitmap(newWidth, newHeight, source.getConfig());
Canvas canvas = new Canvas(dest);
canvas.drawBitmap(source, null, targetRect, null);

return dest;
}

希望对你有帮助

关于java - 在android中缩小图像并使其成为正方形,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34891257/

相关文章:

java - 尝试将图像保存到 firebase 存储时,android studio 出现错误

java - 使用流检测实体的多个属性的重复项

java - Android kotlin - 取消画廊选择时应用程序停止工作

delphi - 加载 Jpg/Gif/Bitmap 并转换为 Bitmap

java - Spring Boot Thymeleaf 字符编码为 UTF-8

android - Airwatch:它如何与版本一起使用?

android - 当应用程序被销毁时,定位服务无法正常工作 Mi 设备

Android - 将事件通知传递给可能不活跃的 Activity 的有效方法?

android - 将 webview 转换为位图

android - 翻译用于绘制位图的矩阵时,它会绘制多个位图