Add Gallery images dynamically in android

前端 未结 2 1975
逝去的感伤
逝去的感伤 2021-02-11 08:33

I\'ve done Gallery of images displayed on emulator by static(i.e images from drawable folder).Now i need to add some images into the list of gallery, dynamically fr

2条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-11 09:01

    Write the file path where the image is saved.

    Environment.getExternalStorageDirectory() gives path of sdcard.

      File f1 = new File(Environment.getExternalStorageDirectory()
                    + File.separator + "test2.png");
    
    
     BitmapFactory.Options o = new BitmapFactory.Options();
     o.inJustDecodeBounds = true;
     Bitmap bitmap = BitmapFactory.decodeStream(new FileInputStream(f), null, o);
    
     imgView.setImageBitmap(bitmap);
    

    If your image is too big size than bitmap will give error so for that you have to write below code to resize image. Pass the file in below function

     Bitmap bitmap = decodeFile(f1);
     imgView.setImageBitmap(bitmap);
    
     private Bitmap decodeFile(File f) {
        try {
            // Decode image size
            BitmapFactory.Options o = new BitmapFactory.Options();
            o.inJustDecodeBounds = true;
            BitmapFactory.decodeStream(new FileInputStream(f), null, o);
    
            // The new size we want to scale to
            final int REQUIRED_SIZE = 150;
    
            // Find the correct scale value. It should be the power of 2.
            int width_tmp = o.outWidth, height_tmp = o.outHeight;
            int scale = 1;
            while (true) {
                if (width_tmp / 2 < REQUIRED_SIZE || height_tmp / 2 < REQUIRED_SIZE)
                    break;
                width_tmp /= 2;
                height_tmp /= 2;
                scale *= 2;
            }
    
            // Decode with inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = scale;
            return BitmapFactory.decodeStream(new FileInputStream(f), null, o2);
    
        } catch (FileNotFoundException e) {
        }
        return null;
    }
    

提交回复
热议问题