在阅读了其他答案并没有找到我想要的东西之后,这是我获取适当缩放位图的方法。这是对 Prabu 答案的改编。
它确保您的图片以不会使照片尺寸变形的方式缩放:
public saveScaledPhotoToFile() {
//Convert your photo to a bitmap
Bitmap photoBm = (Bitmap) "your Bitmap image";
//get its orginal dimensions
int bmOriginalWidth = photoBm.getWidth();
int bmOriginalHeight = photoBm.getHeight();
double originalWidthToHeightRatio = 1.0 * bmOriginalWidth / bmOriginalHeight;
double originalHeightToWidthRatio = 1.0 * bmOriginalHeight / bmOriginalWidth;
//choose a maximum height
int maxHeight = 1024;
//choose a max width
int maxWidth = 1024;
//call the method to get the scaled bitmap
photoBm = getScaledBitmap(photoBm, bmOriginalWidth, bmOriginalHeight,
originalWidthToHeightRatio, originalHeightToWidthRatio,
maxHeight, maxWidth);
/**********THE REST OF THIS IS FROM Prabu's answer*******/
//create a byte array output stream to hold the photo's bytes
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
//compress the photo's bytes into the byte array output stream
photoBm.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
//construct a File object to save the scaled file to
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "Imagename.jpg");
//create the file
f.createNewFile();
//create an FileOutputStream on the created file
FileOutputStream fo = new FileOutputStream(f);
//write the photo's bytes to the file
fo.write(bytes.toByteArray());
//finish by closing the FileOutputStream
fo.close();
}
private static Bitmap getScaledBitmap(Bitmap bm, int bmOriginalWidth, int bmOriginalHeight, double originalWidthToHeightRatio, double originalHeightToWidthRatio, int maxHeight, int maxWidth) {
if(bmOriginalWidth > maxWidth || bmOriginalHeight > maxHeight) {
Log.v(TAG, format("RESIZING bitmap FROM %sx%s ", bmOriginalWidth, bmOriginalHeight));
if(bmOriginalWidth > bmOriginalHeight) {
bm = scaleDeminsFromWidth(bm, maxWidth, bmOriginalHeight, originalHeightToWidthRatio);
} else {
bm = scaleDeminsFromHeight(bm, maxHeight, bmOriginalHeight, originalWidthToHeightRatio);
}
Log.v(TAG, format("RESIZED bitmap TO %sx%s ", bm.getWidth(), bm.getHeight()));
}
return bm;
}
private static Bitmap scaleDeminsFromHeight(Bitmap bm, int maxHeight, int bmOriginalHeight, double originalWidthToHeightRatio) {
int newHeight = (int) Math.min(maxHeight, bmOriginalHeight * .55);
int newWidth = (int) (newHeight * originalWidthToHeightRatio);
bm = Bitmap.createScaledBitmap(bm, newWidth, newHeight, true);
return bm;
}
private static Bitmap scaleDeminsFromWidth(Bitmap bm, int maxWidth, int bmOriginalWidth, double originalHeightToWidthRatio) {
//scale the width
int newWidth = (int) Math.min(maxWidth, bmOriginalWidth * .75);
int newHeight = (int) (newWidth * originalHeightToWidthRatio);
bm = Bitmap.createScaledBitmap(bm, newWidth, newHeight, true);
return bm;
}
这是我的 GitHub Gist 的相应链接:https ://gist.github.com/Lwdthe1/2d1cd0a12f30c18db698