moe
moe

Reputation: 247

android reading an image from SD Card

I'm trying to read an image from my SD Card and I'm not sure if I'm doing it right or not. Need some help please

This is my code for reading it:

String imageInSD = "/sdcard/Hanud/" + c.getString(1) + ".PNG";
        Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);
        ImageView myImageView = (ImageView)findViewById(R.id.imageview);
        myImageView.setImageBitmap(bitmap);

And this is my main file:

<?xml version="1.0" encoding="utf-8"?>
<WebView 
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:id="@+id/webview"
  android:orientation="vertical"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent">

 <!-- <ImageView
    android:id="@+id/image"
    android:scaleType="center"
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    />-->

    <ImageView
  android:id="@+id/imageview"
  android:layout_gravity="center"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:scaleType="center"
  />


  <TextView  
    android:id="@+id/myNameText"
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:text="@string/hello"
  />
</WebView>

Upvotes: 7

Views: 23972

Answers (6)

Abhishek Lokare
Abhishek Lokare

Reputation: 41

You can use the following code. You can choose any image file and you don't need to worry about the directory path as it is also automatically resolved.

Java Version:

import static android.app.Activity.RESULT_OK;

private Bitmap bitmap;
private Uri filePath;
private int GET_IMAGE = 1;
private void showFileChooser() {
    Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
    photoPickerIntent.setType("image/*");
    startActivityForResult(photoPickerIntent, GET_IMAGE);
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == GET_IMAGE && resultCode == RESULT_OK && data != null && data.getData() != null) {

        filePath = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(getActivity().getContentResolver(), filePath);
            imageView.setImageBitmap(bitmap);
        } catch (IOException e) {
            Toast.makeText(this,"Error Loading Image!!!", Toast.LENGTH_SHORT).show()
        }
    }
}

Kotlin Version :

import android.app.Activity.RESULT_OK

private val GET_IMAGE = 1
private lateinit var filePath : Uri
private lateinit var bitmap : Bitmap

private fun selectImage() {
    var photoPickerIntent : Intent = Intent(Intent.ACTION_PICK)
    photoPickerIntent.setType("image/*")
    startActivityForResult(photoPickerIntent, GET_IMAGE)
}


override fun onActivityResult(requestCode: Int, resultCode: Int, data: Intent?) {
    super.onActivityResult(requestCode, resultCode, data)
    if(requestCode == GET_IMAGE && resultCode == RESULT_OK && data != null){
        filePath = data.data

        try{
            bitmap = MediaStore.Images.Media.getBitmap(activity!!.contentResolver, filePath)
            imageView!!.setImageBitmap(bitmap)
        }catch (exception : IOException){
            Toast.makeText(activity,"Error Loading Image!!!", Toast.LENGTH_SHORT).show()
        }
    }
}

Upvotes: 0

Nischitha s
Nischitha s

Reputation: 1

This is the code 

    public class MainActivity extends AppCompatActivity {

    private ImageView mImageView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mImageView= (ImageView) findViewById(imageView);

    }

    public void openImages(View view) {
        Intent intent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.INTERNAL_CONTENT_URI);
        intent.setType("image/*");
        intent.putExtra("crop", "true");
        intent.putExtra("scale", true);
        intent.putExtra("outputX", 256);
        intent.putExtra("outputY", 256);
        intent.putExtra("aspectX", 1);
        intent.putExtra("aspectY", 1);
        intent.putExtra("return-data", true);
        startActivityForResult(intent, 1);
    }
    public void openCamera(View view) {
        Intent cameraIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        startActivityForResult(cameraIntent, 2);
    }
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }

        if (requestCode == 1) {
            final Bundle extras = data.getExtras();
            if (extras != null) {
                //Get image
                Bitmap newProfilePic = extras.getParcelable("data");
                mImageView.setImageBitmap(newProfilePic);

            }
        }
        if(requestCode==2){
            final Bundle bundle=data.getExtras();
            if(bundle !=null){
                Bitmap camera_pic=bundle.getParcelable("data");
                mImageView.setImageBitmap(camera_pic);
            }
        }
    }


}

Upvotes: 0

Wael Hashedi
Wael Hashedi

Reputation: 1

BitmapFactory.Options options = new BitmapFactory.Options(); options.inSampleSize = 3;

Bitmap bitmap = BitmapFactory.decodeFile(f.get(position),options);

Upvotes: 0

AliR
AliR

Reputation: 2085

You can use the following code:

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();

You would need to run FileInputStream in a try/catch block.

Upvotes: 4

Jack Satriano
Jack Satriano

Reputation: 2029

It should be:

String imageInSD = Environment.getExternalStorageDirectory().getAbsolutePath() +"/Hanud/" + c.getString(1) + ".PNG";
        Bitmap bitmap = BitmapFactory.decodeFile(imageInSD);
        ImageView myImageView = (ImageView)findViewById(R.id.imageview);
        myImageView.setImageBitmap(bitmap);

This will ensure you find the correct directory!

Upvotes: 9

Android Developer
Android Developer

Reputation: 7349

First define xml

<? Xml version = “1.0″ encoding = “utf-8″?>
<RelativeLayout xmlns: android = “http://schemas.android.com/apk/res/android”
android: orientation = “vertical”
the android: layout_width = “fill_parent The
android: layout_height = “fill_parent The
android: background = “55 million”
>
<ImageSwitcher / / this control with the Gallery often used, remember
android: id = “@ + the id / in switcher ‘”
the android: layout_width = “wrap_content The
android: layout_height = “350dip The
android: layout_alignParentLeft = “true”
android: layout_alignParentRight = “true”
/>
< Gallery
android: id = “@ + id / mygallery”
the android: layout_width = “fill_parent The
android: layout_height = “80dp”
android: layout_alignParentBottom = “true”
android: layout_alignParentLeft = “true”
android: gravity = “center_vertical”
android: spacing = “16dp”
/>
</ RelativeLayout>

Two. Activity in a custom display

package com.ldci.second.mypnone;

import java.io.File;
import java.util.ArrayList;
import of java.util.List;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import the android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.net.Uri;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.view.View.OnClickListener;
import android.view.animation.AnimationUtils;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.Toast;
import android.widget.ViewSwitcher;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Gallery.LayoutParams;

public class BgPictureShowActivity extends Activity implements
AdapterView.OnItemSelectedListener, ViewSwitcher.ViewFactory {

the private List <String> the ImageList;
private String [] list;
private ImageSwitcher mSwitcher;
public void onCreate (Bundle savedInstanceState) {
super.onCreate (savedInstanceState);
/ / / / Remove the status bar, and display their own program name
/ / GetWindow (). SetFlags (WindowManager.LayoutParams.FLAG_FULLSCREEN,
/ / WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView (R.layout.pictureshow);

The ImageList the getSD ();
list = ImageList.toArray (new String [ImageList.size ()]);

/ * Set the Switcher * /
mSwitcher = (ImageSwitcher) findViewById (R.id.switcher);
mSwitcher.setFactory (this);
/ * Set the load Switcher mode * /
mSwitcher.setInAnimation (AnimationUtils.loadAnimation (this,
android.R.anim.fade_in));
/ * Set output Switcher mode * /
mSwitcher.setOutAnimation (AnimationUtils.loadAnimation (this,
android.R.anim.fade_out));
mSwitcher.setOnClickListener (new OnClickListener () {

public void onClick (View v) the {
Toast.makeText (BgPictureShowActivity.this, “click”, Toast.LENGTH_SHORT). The show ();

}

});

Gallery g = (Gallery) findViewById (R.id.mygallery);

/ * Add several ImageAdapter to and set to the Gallery object * /
g.setAdapter (new ImageAdapter (this, getSD ()));

g.setOnItemSelectedListener (this);

/ * Set a itemclickListener event * /
g.setOnItemClickListener (new OnItemClickListener ()
{
public void the onItemClick (AdapterView, which <?> parent,
View v, int position, long id)
{
Toast.makeText (BgPictureShowActivity.this, “dianjiale”, Toast.LENGTH_SHORT). Show ();
}
});
}

private List <String> getSD ()
{
/ * Set the current path * /
The the List <String> it = the new ArrayList <String> ();
File f = new File (“/ sdcard /”);
File [] files = f.listFiles ();

/ * All the files stored in the ArrayList * /
for (int i = 0; i <files.length; i + +)
{
The File the file = files [i];
if (getImageFile (file.getPath ()))
it.add (file.getPath ());
}
return it;
}

private boolean getImageFile (String fName)
{
a boolean the re;

/ * Get the extension * /
String end = fName.substring (fName.lastIndexOf (“.”) +1,
fName.length ()). toLowerCase ();

/ * Decided by the type of extension The MimeType * /
if (end.equals (“jpg”) | | end.equals (“gif”) | | end.equals (“png”)
| | End.equals (“jpeg”) | | end.equals (“bmp”))
{
re = true;
}
else
{
re = false;
}
return the re;
}

/ * To rewrite BaseAdapter custom one ImageAdapter class * /
public class ImageAdapter the extends BaseAdapter,
{
/ * Declare variables * /
int mGalleryItemBackground;
private Context mContext;
private the List <String> of lis;

/ * ImageAdapter, constructed character * /
the public ImageAdapter (Context c, the List <String> li)
{
mContext = c;
of lis = li;
/ * Res / values ​​/ attrs.xml <declare-styleable> defined
* Gallery attribute * /
TypedArray a = obtainStyledAttributes (R.styleable.Gallery);
/ * Obtain attribute Gallery Index id * /
mGalleryItemBackground = a.getResourceId (
R.styleable.Gallery_android_galleryItemBackground, 0);
/ * Let the object styleable properties can be used repeatedly * /
a.recycle ();
}

/ * A few set to rewrite the getCount, the number of returned images * /
public int the getCount ()
{
return lis.size ();
}
/ * Must override the method getItem, returns the position * /
Public Object getItem (int position)
{
the return position;
}

/ * Must be rewritten getItemId pass and position * /
public long getItemId (int position)
{
the return position;
}

/ * A few set to rewrite the method getView pass and View objects * /
public View getView (int position, View convertView,
Of ViewGroup that the parent)
{
/ * Generate the ImageView object * /
ImageView i = new ImageView (mContext);
/ * Set the picture to imageView object * /
Bitmap bm = BitmapFactory.decodeFile (lis.
get (position). toString ());
i.setImageBitmap (bm);
/ * Reset the image width and height * /
i.setScaleType (ImageView.ScaleType.FIT_XY);
/ * Reset the Layout of the width and height * /
i.setLayoutParams (new Gallery.LayoutParams (136, 88));
/ * Set the Gallery background images * /
i.setBackgroundResource (mGalleryItemBackground);
/ * Pass back to imageView object * /
return i;
}
}

public void onItemSelected (AdapterView <?> parent, View view, int position,
long id) {
The string photoURL = list [position];
Log.i (“A”, String.valueOf (position));

mSwitcher.setImageURI (Uri.parse (photoURL));

}

public void onNothingSelected (AdapterView <?> parent) {
/ / TODO Auto-generated method the stub

}

public View makeView () {
ImageView i = new ImageView (this);
i.setBackgroundColor (0xFF000000);
i.setScaleType (ImageView.ScaleType.FIT_CENTER);
i.setLayoutParams (new ImageSwitcher.LayoutParams (
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
return i;
}
}

This code is very long, to see will certainly be a headache plus DAN pain, but to hold on the MARS God repeatedly warned we in this industry is characterized to be patient. There is a very important thing, in the values ​​file folder, create an xml inside the book:

<? Xml version = “1.0″ encoding = “utf-8″?>
<resources>
<declare-styleable name=”Gallery”>
<attr name=”android:galleryItemBackground” />
</ Declare-styleable
</ Resources>

http://developer.aiwgame.com/gallery-show-an-image-from-android-sd-card.html

Upvotes: 0

Related Questions