From c28ce244eab7ec69dad6595afec701eb865e20d5 Mon Sep 17 00:00:00 2001 From: hugh <1012760428@qq.com> Date: Tue, 20 Jan 2026 23:55:35 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E6=B7=BB=E5=8A=A0=E5=9B=BE=E7=89=87?= =?UTF-8?q?=E5=8A=A0=E8=BD=BD=E5=99=A8?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 实现图片采样和缩放功能 - 使用 RGB_565 降低内存占用 - 自动计算 inSampleSize 优化加载性能 Co-Authored-By: Claude Sonnet 4.5 --- .../cn/hugh/bz/gk2/wallpaper/ImageLoader.java | 70 +++++++++++++++++++ 1 file changed, 70 insertions(+) create mode 100644 app/src/main/java/cn/hugh/bz/gk2/wallpaper/ImageLoader.java diff --git a/app/src/main/java/cn/hugh/bz/gk2/wallpaper/ImageLoader.java b/app/src/main/java/cn/hugh/bz/gk2/wallpaper/ImageLoader.java new file mode 100644 index 0000000..0972018 --- /dev/null +++ b/app/src/main/java/cn/hugh/bz/gk2/wallpaper/ImageLoader.java @@ -0,0 +1,70 @@ +package cn.hugh.bz.gk2.wallpaper; + +import android.content.Context; +import android.graphics.Bitmap; +import android.graphics.BitmapFactory; +import android.util.Log; + +import java.io.File; + +public class ImageLoader { + private static final String TAG = "ImageLoader"; + private final Context context; + + public ImageLoader(Context context) { + this.context = context; + } + + public Bitmap loadImage(String uri, int maxWidth, int maxHeight) { + try { + File file = new File(uri); + if (!file.exists()) { + Log.e(TAG, "File not found: " + uri); + return null; + } + + // First decode with inJustDecodeBounds=true to check dimensions + BitmapFactory.Options options = new BitmapFactory.Options(); + options.inJustDecodeBounds = true; + BitmapFactory.decodeFile(file.getAbsolutePath(), options); + + // Calculate inSampleSize + options.inSampleSize = calculateInSampleSize(options, maxWidth, maxHeight); + + // Decode bitmap with inSampleSize + options.inJustDecodeBounds = false; + options.inPreferredConfig = Bitmap.Config.RGB_565; + + Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options); + + if (bitmap != null) { + // Scale to exact size if needed + bitmap = Bitmap.createScaledBitmap(bitmap, maxWidth, maxHeight, true); + } + + return bitmap; + } catch (Exception e) { + Log.e(TAG, "Failed to load image: " + uri, e); + return null; + } + } + + private int calculateInSampleSize(BitmapFactory.Options options, + int reqWidth, int reqHeight) { + final int height = options.outHeight; + final int width = options.outWidth; + int inSampleSize = 1; + + if (height > reqHeight || width > reqWidth) { + final int halfHeight = height / 2; + final int halfWidth = width / 2; + + while ((halfHeight / inSampleSize) >= reqHeight + && (halfWidth / inSampleSize) >= reqWidth) { + inSampleSize *= 2; + } + } + + return inSampleSize; + } +}