如何从资源中加载图像?

发布于 2024-12-08 08:10:58 字数 952 浏览 0 评论 0原文

我需要从资源中加载图像,以避免在某些特定情况下调整 POT 图像大小时出现 froyo 2.2.2 错误。避免这种情况的方法是从资产目录加载图像文件。

我正在尝试这样做:

String imagePath = "radiocd5.png";
AssetManager mngr = context.getAssets();
// Create an input stream to read from the asset folder
InputStream is = null;
try {
    is = mngr.open(imagePath);
} catch (IOException e1) { e1.printStackTrace();}
    
//Get the texture from the Android resource directory
//InputStream is = context.getResources().openRawResource(R.drawable.radiocd5);
Bitmap bitmap = null;
try {
    //BitmapFactory is an Android graphics utility for images
    bitmap = BitmapFactory.decodeStream(is);

} finally {
    //Always clear and close
    try {
        is.close();
        is = null;
    } catch (IOException e) {}
}

但是我在 is.close(); 线上收到 NullPointerException;

我捕获了 FileNotFoundException:radicd5.png,但该文件位于我的资产目录中:S

什么我做得不好吗?该文件名为 radiocd5.png,位于 assets 目录中

i need to load a image from assets to avoid a froyo 2.2.2 bug resizing POT images in some particular cases. The way to avoid it is loading the image files from assets dir.

I'm trying to do with this:

String imagePath = "radiocd5.png";
AssetManager mngr = context.getAssets();
// Create an input stream to read from the asset folder
InputStream is = null;
try {
    is = mngr.open(imagePath);
} catch (IOException e1) { e1.printStackTrace();}
    
//Get the texture from the Android resource directory
//InputStream is = context.getResources().openRawResource(R.drawable.radiocd5);
Bitmap bitmap = null;
try {
    //BitmapFactory is an Android graphics utility for images
    bitmap = BitmapFactory.decodeStream(is);

} finally {
    //Always clear and close
    try {
        is.close();
        is = null;
    } catch (IOException e) {}
}

But i am getting NullPointerException on the line is.close();

i capture a FileNotFoundException: radiocd5.png, but that file is on my assets directory :S

What am i doing bad? The file is called radiocd5.png and it is on the assets directory

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

浅听莫相离 2024-12-15 08:10:58

您可以按照我的教程来显示资产中的数据: https://xjaphx.wordpress.com/2011/10/02/store-and-use-files-in-assets/
带有加载图像和要显示的文本的示例。

我现在添加了所提供链接的相关部分
(如果发生地震或其他什么情况);-) Taifun

// load image
try {
    // get input stream
    InputStream ims = getAssets().open("avatar.jpg");
    // load image as Drawable
    Drawable d = Drawable.createFromStream(ims, null);
    // set image to ImageView
    mImage.setImageDrawable(d);
}
catch(IOException ex) {
    return;
}

You can follow my tutorials on displaying data from Assets: https://xjaphx.wordpress.com/2011/10/02/store-and-use-files-in-assets/
The sample with loading image and text to display.

I now added the relevant part of the provided link
(in case of earthquake or something) ;-) Taifun

// load image
try {
    // get input stream
    InputStream ims = getAssets().open("avatar.jpg");
    // load image as Drawable
    Drawable d = Drawable.createFromStream(ims, null);
    // set image to ImageView
    mImage.setImageDrawable(d);
}
catch(IOException ex) {
    return;
}
长伴 2024-12-15 08:10:58

不要使用资源目录,而是将文件放入 /res/raw,然后您可以使用以下 URI 访问它: android.resource://com.your.packagename/" + R.raw.radiocd5< /代码>

Instead of using the assets dir, put the file into /res/raw, and you can then access it using the following URI: android.resource://com.your.packagename/" + R.raw.radiocd5

回心转意 2024-12-15 08:10:58
try {
    InputStream istr = this.context.getAssets().open(P.strImage);
    //set drawable from stream
    this.imgProduct.setImageDrawable(Drawable.createFromStream(istr, null));
} catch (IOException e) {
    e.printStackTrace();
}
try {
    InputStream istr = this.context.getAssets().open(P.strImage);
    //set drawable from stream
    this.imgProduct.setImageDrawable(Drawable.createFromStream(istr, null));
} catch (IOException e) {
    e.printStackTrace();
}
短叹 2024-12-15 08:10:58
protected String openImageInAssets(String imageName) {
    String encodedImageBase64 = "";
    AssetManager assetManager = getAssets();
    InputStream fileStream = null;
    try {
        fileStream = assetManager.open(imageName);
        if (fileStream != null) {
            // BitmapFactory.Options bfo = new BitmapFactory.Options();
            // bfo.inPreferredConfig = Bitmap.Config.ARGB_8888;
            // Bitmap bitmap = BitmapFactory.decodeStream(fileStream, null, bfo);

            Bitmap bitmap = BitmapFactory.decodeStream(fileStream);
            // Convert bitmap to Base64 encoded image for web
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            // to get image extension file name split the received
            int fileExtensionPosition = imageName.lastIndexOf('.');
            String fileExtension = imageName.substring(fileExtensionPosition+1);
            // Log.d(IConstants.TAG,"fileExtension: " + fileExtension);

            if (fileExtension.equalsIgnoreCase("png")) {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                // Log.d(IConstants.TAG,"fileExtension is PNG");
            } else if (fileExtension.equalsIgnoreCase("jpg") || fileExtension.equalsIgnoreCase("jpeg")) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
                // Log.d(TAG,"fileExtension is JPG");
            }

            byte[] byteArray = byteArrayOutputStream.toByteArray();
            String imgageBase64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
            encodedImageBase64 = "data:image/png;base64," + imgageBase64;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return encodedImageBase64="";
    } finally {
        //Always clear and close
        try {
            if (fileStream != null) {
                fileStream.close();
                fileStream = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Log.d(TAG,"encodedImageBase64: " + encodedImageBase64);
    return encodedImageBase64;
}
protected String openImageInAssets(String imageName) {
    String encodedImageBase64 = "";
    AssetManager assetManager = getAssets();
    InputStream fileStream = null;
    try {
        fileStream = assetManager.open(imageName);
        if (fileStream != null) {
            // BitmapFactory.Options bfo = new BitmapFactory.Options();
            // bfo.inPreferredConfig = Bitmap.Config.ARGB_8888;
            // Bitmap bitmap = BitmapFactory.decodeStream(fileStream, null, bfo);

            Bitmap bitmap = BitmapFactory.decodeStream(fileStream);
            // Convert bitmap to Base64 encoded image for web
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

            // to get image extension file name split the received
            int fileExtensionPosition = imageName.lastIndexOf('.');
            String fileExtension = imageName.substring(fileExtensionPosition+1);
            // Log.d(IConstants.TAG,"fileExtension: " + fileExtension);

            if (fileExtension.equalsIgnoreCase("png")) {
                bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
                // Log.d(IConstants.TAG,"fileExtension is PNG");
            } else if (fileExtension.equalsIgnoreCase("jpg") || fileExtension.equalsIgnoreCase("jpeg")) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
                // Log.d(TAG,"fileExtension is JPG");
            }

            byte[] byteArray = byteArrayOutputStream.toByteArray();
            String imgageBase64 = Base64.encodeToString(byteArray, Base64.DEFAULT);
            encodedImageBase64 = "data:image/png;base64," + imgageBase64;
        }
    } catch (IOException e) {
        e.printStackTrace();
        return encodedImageBase64="";
    } finally {
        //Always clear and close
        try {
            if (fileStream != null) {
                fileStream.close();
                fileStream = null;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    // Log.d(TAG,"encodedImageBase64: " + encodedImageBase64);
    return encodedImageBase64;
}
相思碎 2024-12-15 08:10:58

这是另一种方法

setImageBitmap(BitmapFactory.decodeStream(assets.open("photo.jpg")))

Here is an alternative way

setImageBitmap(BitmapFactory.decodeStream(assets.open("photo.jpg")))
泪冰清 2024-12-15 08:10:58

另一个版本,在片段内:

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    root = inflater.inflate(R.layout.createrestaurant_layout, container, false);
    Resources res = getResources();
    img = (ImageView) root.findViewById(R.id.img);
    AssetManager amanager = res.getAssets();
    try {
        InputStream imageStream = amanager.open("restaurant.jpg");
        Drawable drawable = new BitmapDrawable(res, imageStream);
        img.setImageDrawable(drawable);
    }  catch (Exception e) {
        e.printStackTrace();
    }
}

这个过程在 iOS/UIKit 或 iOS/SwiftUI 中似乎要简单得多。

Another version, inside a fragment:

@Override
public View onCreateView(@NonNull LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    root = inflater.inflate(R.layout.createrestaurant_layout, container, false);
    Resources res = getResources();
    img = (ImageView) root.findViewById(R.id.img);
    AssetManager amanager = res.getAssets();
    try {
        InputStream imageStream = amanager.open("restaurant.jpg");
        Drawable drawable = new BitmapDrawable(res, imageStream);
        img.setImageDrawable(drawable);
    }  catch (Exception e) {
        e.printStackTrace();
    }
}

This process seems much simpler in iOS/UIKit or iOS/SwiftUI.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文