如何用可用的高分辨率图像参考替换 URL 字符串末尾的低分辨率图像参考

How to replace low res image reference at end of URL string with the higher res image reference available

从 API 我从类似于此格式的 URL 字符串中获取缩略图: https://website.com/05b8a817448d0e2/0_167_3000_1799/500.jpg。但是,对于 android 应用程序开发来说,它看起来很脏。

API 没有可用的高分辨率图像。但是,我发现通过更改 URL 的末尾,图像存在于 1000px 甚至 2000px。

我想将 URL 字符串更改为在同一位置存在的具有改进后缀的高分辨率版本: https://website.com/05b8a817448d0e2/0_167_3000_1799/1000.jpg

额外要求:

所以解决方案需要比我当前的编码能力更强大。

这是我在 Android Studio 中的代码块,它工作正常,但不包含额外的要求。我只在 Java 和 Android Studio 中编码了几个月,所以可能存在一些问题:

 /**
 * Load an image from a URL and return a {@link Bitmap}
 *
 * @param url string of the URL link to the image
 * @return Bitmap of the image
 */
private static Bitmap downloadBitmap(String url) {
    Bitmap bitmap = null;
    String newUrlString = url;

    try {
        // Change 500px image to 1000px image
        URL oldUrl = new URL(url);
        if (url.endsWith("500.jpg")) {
            newUrlString = oldUrl.toString().replaceFirst("500.jpg", "1000.jpg");
        }

        InputStream inputStream = new URL(newUrlString).openStream();
        bitmap = BitmapFactory.decodeStream(inputStream);
    } catch (Exception e) {
        Log.e(LOG_TAG, e.getMessage());
    }
    return bitmap;
}

尝试以下操作:

protected class ImageLoader extends AsyncTask<String, Void, Bitmap> {
        protected Bitmap doInBackground(String... urls) {
            Bitmap bitmap = null;
            String originalUrl = urls[0];
            String url = urls[0].replaceFirst("/500.", "/1000.");
            try {
                InputStream inputStream = new URL(url).openStream();
                bitmap = BitmapFactory.decodeStream(inputStream);
            } catch (Exception e) {
                try {
                    InputStream inputStream = new URL(originalUrl).openStream();
                    bitmap = BitmapFactory.decodeStream(inputStream);
                } catch (Exception ignored) {
                }
            }
            return bitmap;
        }

        protected void onPostExecute(Bitmap bitmap) {
            //do whatever you want with the result.
            if(bitmap!=null)
            image.setImageBitmap(bitmap);
        }
    }

我在这里所做的是,我创建了一个名为 ImageLoader 的 AsyncTask(因为您的原始代码会抛出 NetworkOnMainThreadException)。它将处理请求图像 url;如果无法获取 1000px 版本,它将故障转移到 500px 版本的图像。 希望这有帮助。