How to load a image from assets?

前端 未结 6 854
傲寒
傲寒 2020-11-29 06:28

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.

6条回答
  •  孤独总比滥情好
    2020-11-29 06:49

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

提交回复
热议问题