2016-01-20 31 views
2

我需要一种将图像缩放到78x78的方法。我已经切割图像的一部分了,像这样的发现,这样做的方法:缩小比例并在android中制作图像正方形

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

,但我需要保持尽可能多的图像成为可能。我曾经想过缩放图像,然后将它缩小:

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

但当然这会产生一个被压扁的方形图像。

任何人都可以建议我如何创建一个78x78图像,不重新调整和保持尽可能多的原始图像尽可能?

+0

是什么形状的原始图像?当你说压扁你的意思是形状改变了吗? – Knells

+0

“挤压”或调整图像大小的替代方法是采用它。在这种情况下,你想扔掉哪部分图像? –

+0

各种尺寸。总是150高或宽,但对面总是不同。 – user3746428

回答

1

从我的理解,你应该缩小和中心裁剪图像。试试这个代码。

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; 
} 

希望它可以帮助

0

试试这个:

Bitmap image = Bitmap.createScaledBitmap(testImage, (int) 78 * (testImage.getWidth()/testImage.getHeight()), 78, true); 
image = Bitmap.createBitmap(image, (int) (image.getWidth() - 78)/2, 78); 

没有测试过这一点,因为我对我的方式睡觉,但它应该完成你想要的,只要你的形象的宽度大于或等于它的高度

无论如何,我建议你使用BufferedImage而不是位图。

0

这里的想法是调整您的图像使用相同的宽度和高度调整大小率保持较小的尺寸在78.之后,您可以使用基于中心点的作物来获取图像的中间,并使其平方图片。

 Image srcImage; 
     int widthSrc = 150; 
     int heightSrc = 180; 
     float resizeRate = 78/min(widthSrc, heightSrc); 
     Image resizedImage = resizeImage($srcImage, resizeRate); 
     int widthDest = 78; 
     int heightDest = 78; 
     int cropX = ($widthSrc - $widthDest)/2; 
     int cropY = ($heightSrc - $heightDest)/2; 
     Image croppedImage = cropImage(resizedImage,$widthDest, $heightDest, $cropX, $cropY); 

如果图像已经是正方形,您可以跳过裁剪部分。