Skip to content

Commit

Permalink
Obey maximum image width (from blog settings) when uploading images f…
Browse files Browse the repository at this point in the history
…rom visual editor
  • Loading branch information
aforcier committed Oct 5, 2015
1 parent 5bc77ff commit 62266e2
Showing 1 changed file with 56 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -20,6 +20,7 @@
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.MimeTypeMap;
import android.widget.ImageView;

import org.apache.http.HttpEntity;
Expand All @@ -31,6 +32,7 @@
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.lang.ref.WeakReference;
Expand Down Expand Up @@ -396,6 +398,60 @@ public static Bitmap getScaledBitmapAtLongestSide(Bitmap bitmap, int targetSize)
return Bitmap.createScaledBitmap(bitmap, targetWidth, targetHeight, true);
}

/**
* Given the path to an image, resize the image down to within a maximum width
* @param path the path to the original image
* @param maxWidth the maximum allowed width
* @return the path to the resized image
*/
public static String createResizedImageWithMaxWidth(Context context, String path, int maxWidth) {
File file = new File(path);
if (!file.exists()) {
return path;
}

String mimeType = MediaUtils.getMediaFileMimeType(file);
if (mimeType.equals("image/gif")) {
// Don't rescale gifs to maintain their quality
return path;
}

String fileName = MediaUtils.getMediaFileName(file, mimeType);
String fileExtension = MimeTypeMap.getFileExtensionFromUrl(fileName).toLowerCase();

int[] dimensions = getImageSize(Uri.fromFile(file), context);
int orientation = getImageOrientation(context, path);

if (dimensions[0] <= maxWidth) {
// Image width is within limits; don't resize
return path;
}

// Create resized image
byte[] bytes = ImageUtils.createThumbnailFromUri(context, Uri.parse(path), maxWidth, fileExtension, orientation);

if (bytes != null) {
try {
File resizedImageFile = File.createTempFile("wp-image-", fileExtension);
FileOutputStream out = new FileOutputStream(resizedImageFile);
out.write(bytes);
out.close();

String tempFilePath = resizedImageFile.getPath();

if (!TextUtils.isEmpty(tempFilePath)) {
return tempFilePath;
} else {
AppLog.e(AppLog.T.POSTS, "Failed to create resized image");
}
} catch (IOException e) {
AppLog.e(AppLog.T.POSTS, "Failed to create image temp file");
}
}

return path;
}

/**
* nbradbury - 21-Feb-2014 - similar to createThumbnail but more efficient since it doesn't
* require passing the full-size image as an array of bytes[]
Expand Down

0 comments on commit 62266e2

Please sign in to comment.