gpt4 book ai didi

java - Assets 中的图像看不到

转载 作者:行者123 更新时间:2023-12-01 12:08:12 24 4
gpt4 key购买 nike

如何获取 android 中 resdrawable 或 asset 中的所有图像并将其放入外部存储中?请帮我。这是我在目录中的代码:

最佳答案

所有图像保存在R.drawable中并不是最好的主意。最好保存特定图像而不是全部图像。但是,您可以按照以下方式保存所有图像,如R.drawable中指定的:

public static void saveAllDrawablesToSdcard(final Context context, final File directory) throws Exception {
new Thread() {

@Override
public void run() {
try {
directory.mkdirs();
final Field[] fields = R.drawable.class.getFields();
final Resources res = context.getResources();
for (Field field : fields) {
final int id = (Integer) field.get(null);
final Drawable drawable = res.getDrawable(id);
final Bitmap bitmap = drawableToBitmap(drawable);
final File file = new File(directory, field.getName() + ".png");
saveBitmapAsPng(bitmap, file.getAbsolutePath());
}
} catch (Exception e) {
}
}
}.start();
}

/**
* Converts a {@link Drawable} to a {@link Bitmap}
*
* @param drawable
* The {@link Drawable} to convert
* @return The converted {@link Bitmap} or {@code null} if it was unable to be converted.
*/
public static Bitmap drawableToBitmap(final Drawable drawable) {
if (drawable instanceof BitmapDrawable) {
return ((BitmapDrawable) drawable).getBitmap();
}
final int height = drawable.getIntrinsicHeight();
final int width = drawable.getIntrinsicWidth();
if (width <= 0 || height <= 0) {
return null;
}
final Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
final Canvas canvas = new Canvas(bitmap);
drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight());
drawable.draw(canvas);
return bitmap;
}

/**
* Saves a {@link Bitmap} as a PNG file.
*
* @param bmp
* a {@link Bitmap}
* @param path
* the path to save the bitmap to
* @return {@code true} if successfully created.
*/
public static final boolean saveBitmapAsPng(final Bitmap bitmap, final String path) {
try {
final File file = new File(path);
final File parent = file.getParentFile();
if (parent != null && !parent.exists()) {
parent.mkdirs();
}
final FileOutputStream fos = new FileOutputStream(file, false);
bitmap.compress(Bitmap.CompressFormat.PNG, 100 /* ignored for PNG */, fos);
fos.flush();
fos.close();
} catch (final Exception e) {
return false;
}
return true;
}

关于java - Assets 中的图像看不到,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27436301/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com