在閱讀其他答案並沒有準確找到我想要的內容之後,我的方法是獲取適當縮放的位圖。這是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 if (bmOriginalHeight > bmOriginalWidth){
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.max(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.max(maxWidth, bmOriginalWidth * .75);
int newHeight = (int) (newWidth * originalHeightToWidthRatio);
bm = Bitmap.createScaledBitmap(bm, newWidth, newHeight, true);
return bm;
}
這裏有一個對應的鏈接到我的GitHub的要點是:https://gist.github.com/Lwdthe1/2d1cd0a12f30c18db698
意味着我應該嘗試少於100像80或70? –
是的,這應該有幫助 – Gooziec
Gooziec:你好,仍然我得到相同的圖像大小,> 1 MB ... –