Display jpg from sdcard android - java

I cant get this to work anymore
Here is my code:
ImageView jpgView = (ImageView)findViewById(R.id.ImageView01);
String myJpgPath = "/sdcard/pic.jpg";
jpgView.setVisibility(View.VISIBLE);
//jpgView.setScaleType(ImageView.ScaleType.FIT_CENTER);
jpgView.setAdjustViewBounds(true);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
Bitmap bm = BitmapFactory.decodeFile(myJpgPath, options);
jpgView.setImageBitmap(bm);
Can anyone help?

You can just use bitmapdrawable, e.g.
ImageView jpgView = (ImageView)findViewById(R.id.ImageView01);
String myJpgPath = "/sdcard/pic.jpg";
BitmapDrawable d = new BitmapDrawable(getResources(), myJpgPath);
jpgView.setImageDrawable(d);

The image won't be shown if you open the emulator directly from the eclipse, by clicking run. You'll be able to access the SD card if you start the emulator using the command line, then click your app on the emulator.

Related

Large scrolled image android studio

I have a problem with loading a large image.
I have to make a map/background with a size of 3556 x 2000 pixels.
I try this:
https://developer.android.com/topic/performance/graphics/load-bitmap.html
But it looks like it does not work properly for me. (Exception: out of memory)
This is my background:
scr.hu/8p0mdz - Screenshooter
I marked with black square the area that is visible on the phone for user. Of course, user can zoom in or out the visible area.
I can't use libgdx. I want to use only android libraries. I have no idea how i should start my work. I don't ask for a code(i will gladly accept the code), but i want to find out what i should start with.
In this background, will be drawn other images(buildings). When game will be start, resources need to be loaded into memory. In libgdx i can use AssetManager. In my case when i use
https://developer.android.com/reference/android/content/res/AssetManager.html
it should be enough?
I hope you understand my problem.
This is not a trivial problem, so I think there is no easy solution. But there're few things which could help:
You can control amount of allocated memory for your bitmap:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
options.inPreferredConfig = Bitmap.Config.RGB_565;
//RGB_565 color format requires way less memory than ARGB_8888
There is BitmapRegionDecoder class which loads just a part of bitmap.
BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance("path", false);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap partOfBitmap = decoder.decodeRegion(new Rect(0, 0, 100, 100), options);
Using BitmapRegionDecoder you can develop your custom View which handles user scroll events and loads into memory only visible image regions and destroys not visible.
I try to solve this as above:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_planet);
int WIDTH = 0;
int HEIGHT = 0;
backgroundJungle = (ImageView)findViewById(R.id.backgroundJungle);
InputStream is = null;
try {
Drawable drawable = getResources().getDrawable(R.drawable.junglemap);
BitmapDrawable bitmapDrawable = (BitmapDrawable) drawable;
Bitmap bitmap = bitmapDrawable.getBitmap();
WIDTH = bitmap.getWidth();
HEIGHT = bitmap.getHeight();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
is = new ByteArrayInputStream(stream.toByteArray());
} catch (Exception ex) {
ManagerException(ex);
}
try {
if (is != null) {
BitmapRegionDecoder decoder = BitmapRegionDecoder.newInstance(is, false);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
Bitmap partOfBitmap = decoder.decodeRegion(new Rect(0,0,2500,2500),options);
backgroundJungle.setImageBitmap(partOfBitmap);
Toast.makeText(getApplicationContext(), WIDTH + " " + HEIGHT, Toast.LENGTH_SHORT).show();
}
} catch (IOException ex) {
ManagerException(ex);
}
}
But bitmap has size 9335 x 5250, but my image has 3556 x 2000.

Android : FileNotFoundException when trying to get an image from Uri

I am trying to get an image's width and height in order to rezize it in case it is too big before showing it. My method receive an uri of the image but I always get a FileNotFoundException when trying to decode it using BitmapFactory.
Here is a sample of my code :
Uri myUri;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(new File(myUri.getPath()).getAbsolutePath(), options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
Decode File returns throws a FileNotFoundException here. However, I can still show the image using the uri without using a bitmap factory using this :
Uri myUri;
Bitmap myBitmap = MediaStore.Images.Media.getBitmap(context.getContentResolver(), myUri);
The problem with this code is that the returned bitmap might cause an OutofMemoryError when using big images.
When I debug my Uri, I get this :
content://com.android.providers.media.documents/document/image%3A20472
UPDATE || Here is the working code
Uri myUri;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
// This is the part that changed
InputStream inputStream = context.getApplicationContext().getContentResolver().openInputStream(myUri);
BitmapFactory.decodeStream(inputStream,new Rect(),options);
int imageHeight = options.outHeight;
int imageWidth = options.outWidth;
All of this of course surrounded by try/catch.
Use decodeStream instead of decodeFile.
Open the stream with getContentResolver().openInputStream(myUri).
After playing around with this for a while, I think the issue is probably that the image file really isn't there.
If you are attempting to access a local file on your computer, that file won't be in the Android sandbox where the app is actually running. You'll need to add it to the app as a resource, then access it as a resource instead of a file.
If you are attempting to access a web image, you need to download it first. The AbsolutePath of a web image 'http://example.com/example.jpg' would be '/example.jpg', which won't do you much good when you try to open it.

OutOfMemory issue loading several pictures

I have nine pictures that I want to load at the start of an activity, and I'm getting problems of OutOfMemory exceptions. At first I loaded them directly in the xml setting its src. So after getting java.lang.OutOfMemory I realized that maybe I needed to load the pictures more efficiently and I created this loop to be executed at the begining of the activity:
for(int i=0;i<9;i++){
String background = "background"+(i+1);
int idDrawable = getResources().getIdentifier(background, "drawable", getPackageName());
int idPicture = getResources().getIdentifier(background, "id", getPackageName());
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), idDrawable, options);
options.inJustDecodeBounds = false;
ImageView image = (ImageView) findViewById(idPicture);
image.setImageBitmap(BitmapFactory.decodeResource(getResources(), idDrawable, options));
}
But I still have the same OutOfMemory issue, any ideas on what am I doing wrong?
Use following code.
Change this code
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeResource(getResources(), idDrawable, options);
to
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
options.inSampleSize = 4;
BitmapFactory.decodeResource(getResources(), idDrawable, options);
and remove this line
options.inJustDecodeBounds = false;
Little bit of googeling and searching by yourself would lead you to that Android Developers HowTo
http://developer.android.com/training/displaying-bitmaps/load-bitmap.html

Create a Bitmap/Drawable from file path

I'm trying to create a Bitmap or Drawable from existing file path.
String path = intent.getStringExtra("FilePath");
BitmapFactory.Options option = new BitmapFactory.Options();
option.inPreferredConfig = Bitmap.Config.ARGB_8888;
mImg.setImageBitmap(BitmapFactory.decodeFile(path));
// mImg.setImageBitmap(BitmapFactory.decodeFile(path, option));
// mImg.setImageDrawable(Drawable.createFromPath(path));
mImg.setVisibility(View.VISIBLE);
mText.setText(path);
But setImageBitmap(), setImageDrawable() doesn't show an image from the path. I've printed path with mText and it looks like : /storage/sdcard0/DCIM/100LGDSC/CAM00001.jpg
What am i doing wrong? Anyone can help me?
Create bitmap from file path:
File sd = Environment.getExternalStorageDirectory();
File image = new File(sd+filePath, imageName);
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
Bitmap bitmap = BitmapFactory.decodeFile(image.getAbsolutePath(),bmOptions);
bitmap = Bitmap.createScaledBitmap(bitmap,parent.getWidth(),parent.getHeight(),true);
imageView.setImageBitmap(bitmap);
If you want to scale the bitmap to the parent's height and width then use Bitmap.createScaledBitmap function.
I think you are giving the wrong file path.
It works for me:
File imgFile = new File("/sdcard/Images/test_image.jpg");
if(imgFile.exists()){
Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());
//Drawable d = new BitmapDrawable(getResources(), myBitmap);
ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
myImage.setImageBitmap(myBitmap);
}
Edit:
If above hard-coded sdcard directory is not working in your case, you can fetch the sdcard path:
String sdcardPath = Environment.getExternalStorageDirectory().toString();
File imgFile = new File(sdcardPath);
here is a solution:
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
Well, using the static Drawable.createFromPath(String pathName) seems a bit more straightforward to me than decoding it yourself... :-)
If your mImg is a simple ImageView, you don't even need it, use mImg.setImageUri(Uri uri) directly.
For Drawable -
Drawable drawable = Drawable.createFromPath(your path in string);
For Bitmap -
Bitmap bitmap = BitmapFactory.decodeFile(your path in string);
How simple it was hope you like
static ArrayList< Drawable> d;
d = new ArrayList<Drawable>();
for(int i=0;i<MainActivity.FilePathStrings1.size();i++) {
myDrawable = Drawable.createFromPath(MainActivity.FilePathStrings1.get(i));
d.add(myDrawable);
}
you can't access your drawables via a path, so if you want a human readable interface with your drawables that you can build programatically.
declare a HashMap somewhere in your class:
private static HashMap<String, Integer> images = null;
//Then initialize it in your constructor:
public myClass() {
if (images == null) {
images = new HashMap<String, Integer>();
images.put("Human1Arm", R.drawable.human_one_arm);
// for all your images - don't worry, this is really fast and will only happen once
}
}
Now for access -
String drawable = "wrench";
// fill in this value however you want, but in the end you want Human1Arm etc
// access is fast and easy:
Bitmap wrench = BitmapFactory.decodeResource(getResources(), images.get(drawable));
canvas.drawColor(Color .BLACK);
Log.d("OLOLOLO",Integer.toString(wrench.getHeight()));
canvas.drawBitmap(wrench, left, top, null);

Read an Image/file from External storage Android

I'm trying to load an image from external storage. I set the permissions, I tried different ways, but none of them works.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(file.toString());
tv.setImageBitmap(bitmap);
and this one,
FileInputStream streamIn = new FileInputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(streamIn);
tv.setImageBitmap(bitmap);
streamIn.close();
If i have file abc.jpg on the sdcard then:
String photoPath = Environment.getExternalStorageDirectory() + "/abc.jpg";
and to get bitmap.
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
or
Bitmap bitmap1 = BitmapFactory.decodeFile(photoPath);
to avoide out of memory error I suggest you use the below code...
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap b = BitmapFactory.decodeFile(photoPath, options);
To avoid above issue you can use Picasso (A powerful image downloading and caching library for Android)
Documentation
How To?
Picasso.with(context).load("file:///android_asset/DvpvklR.png").into(imageView2);
Picasso.with(context).load(new File(...)).into(imageView3);
File sdCard = Environment.getExternalStorageDirectory();
File directory = new File (sdCard.getAbsolutePath() + "/Pictures");
File file = new File(directory, "image_name.jpg"); //or any other format supported
FileInputStream streamIn = new FileInputStream(file);
Bitmap bitmap = BitmapFactory.decodeStream(streamIn); //This gets the image
streamIn.close();
Get the path of the image from your folder as below. And then decode the file as a bitmap.
File file= new File(android.os.Environment.getExternalStorageDirectory(),"Your folder");
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath())
If you have a file path, just use BitmapFactory directly, but tell it to use a format that preserves alpha:
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(photoPath, options);
selected_photo.setImageBitmap(bitmap);
There is a function called
createFromPath(String)
in the Drawable class.
So the statement
String path="/storage/..<just type in the path>";
Drawable.createFromPath(path);
will return a drawable object

Categories