feat: 添加图片加载器

- 实现图片采样和缩放功能
- 使用 RGB_565 降低内存占用
- 自动计算 inSampleSize 优化加载性能

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
This commit is contained in:
hughhuangandClaude Sonnet 4.5 committed 2026-01-20 23:55:35 +08:00
1 parent 9d6b34cde7
commit c28ce244ea
1 file changed
+70
@@ -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;
}
}