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; + } +}