MediaStore.Images.Thumbnails.getThumbnail
是 Android 平台上的一个方法,用于获取图片的缩略图。如果这个方法返回 null
,可能有以下几种原因:
以下是一个完整的示例代码,展示了如何获取图片的缩略图:
import android.Manifest;
import android.content.ContentUris;
import android.content.pm.PackageManager;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.os.Environment;
import android.provider.MediaStore;
import androidx.core.app.ActivityCompat;
import androidx.core.content.ContextCompat;
import java.io.File;
public class ThumbnailHelper {
private static final int REQUEST_CODE = 123;
public Bitmap getThumbnail(String imagePath) {
if (ContextCompat.checkSelfPermission(this, Manifest.permission.READ_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
ActivityCompat.requestPermissions(this, new String[]{Manifest.permission.READ_EXTERNAL/WebAPI_STORAGE}, REQUEST_CODE);
return null;
}
Uri imageUri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
String[] projection = {MediaStore.Images.Media._ID};
Cursor cursor = getContentResolver().query(imageUri, projection, null, null, null);
if (cursor != null && cursor.moveToFirst()) {
int id = cursor.getInt(cursor.getColumnIndex(MediaStore.Images.Media._ID));
Uri imageUri = ContentUris.withAppendedId(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, id);
cursor.close();
Bitmap thumbnail = MediaStore.Images.Thumbnails.getThumbnail(getContentResolver(), id, MediaStore.Images.Thumbnails.MINI_KIND, null);
if (thumbnail != null) {
return thumbnail;
} else {
// 尝试等待缩略图生成
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
return MediaStore.Images.Thumbnails.getThumbnail(getContentResolver(), id, MediaStore.Images.Thumbnails.MINI_KIND, null);
}
}
return null;
}
}
希望这些信息能帮助你解决问题。
领取专属 10元无门槛券
手把手带您无忧上云