Skip to content

Instantly share code, notes, and snippets.

@liaohuqiu
Created February 20, 2017 06:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save liaohuqiu/7b47eb97d04791b3fe589641775ac109 to your computer and use it in GitHub Desktop.
Save liaohuqiu/7b47eb97d04791b3fe589641775ac109 to your computer and use it in GitHub Desktop.
public class ImageUrlManager {
private static final String HTTP = "http";
private static final String GIF = ".gif";
private static final String KEY_IMAGEMOGR2 = "?imageMogr2";
/**
* Refer to: https://portal.qiniu.com/myTickets/ticketDetail?id=36037
* There is one bug in qiniu.com, they may fail to convert gif to
* animated webp.
* So they suggested for now, add '/ignore-error/1' flag, if converting
* failed,
* The original image will be returned instead of one error msg.
*/
private static final String ONLY_WEBP = "?imageMogr2/format/webp/ignore-error/1";
private static int[] sSize = new int[]{1080, 960, 640, 480, 320, 180,
160, 80, 60};
private static SEImageUrlManager sInstance;
private Map<Integer, String> mCache;
private SEImageUrlManager() {
mCache = new HashMap<Integer, String>();
}
public synchronized static SEImageUrlManager getInstance() {
if (sInstance == null) {
sInstance = new SEImageUrlManager();
}
return sInstance;
}
public synchronized String getRemoteUrl(String url, int size) {
if (TextUtils.isEmpty(url)) {
return url;
}
if (!url.startsWith(HTTP)) {
return url;
}
if (url.startsWith(KEY_IMAGEMOGR2)) {
return url;
}
if (url.endsWith(GIF)) {
return url + ONLY_WEBP;
}
if (!mCache.containsKey(size)) {
String postFix = "";
for (int i = sSize.length - 1; i >= 0; i--) {
if (sSize[i] >= size) {
// postFix = String.format
// ("?imageMogr2/format/webp/thumbnail/%s>", sSize[i]);
//
// Refer to: https://portal.qiniu
// .com/myTickets/ticketDetail?id=36037
//
// There is one bug in qiniu.com, they may fail to
// convert gif to animated webp.
// So they suggested for now, add '/ignore-error/1' flag,
// if converting failed,
// The original image will be returned instead of one
// error msg.
postFix = String.format
("?imageMogr2/format/webp/thumbnail/%s>/ignore" +
"-error/1", sSize[i]);
break;
}
}
mCache.put(size, postFix);
}
return url + mCache.get(size);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment