在我的应用程序中显示画廊的图像 [英] Showing images of gallery in my application

查看:22
本文介绍了在我的应用程序中显示画廊的图像的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从它的数据库中检索图库中的所有图像,并希望在我的应用程序中以 gridview 显示.请告诉怎么做..

I want to retrieve all the images from gallery from its database and want to display in my application in gridview. please tell how to do it..

推荐答案

import java.io.BufferedInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;

import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.drawable.BitmapDrawable;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemLongClickListener;




/**
 * Class will Display all gallery images in grid view This class has the
 * functionality to move images from public gallery to Private
 * 
 */

public class AndroidGallery extends Activity implements OnItemLongClickListener {

    private GridView sdcardImages;
    private ImageAdapter imageAdapter;

    private String TAG = this.getClass().getSimpleName();
    private ArrayList<LoadedImage> photos = new ArrayList<LoadedImage>();

    private String thumb_Image_Path;
    private String crypto = null;

    private FileInputStream is = null;
    private BufferedInputStream bis = null;
    private Bitmap bitmap;
    private ByteArrayOutputStream bytes;
    private File galleryThumbFile, galleryImageFile,galleryThumbFolder, galleryImageFolder;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);

        setContentView(R.layout.sdcard);


    }




    @Override
    protected void onResume() {
        // TODO Auto-generated method stub
        super.onResume();

        photos.clear();                             // If photos array list has any previous value then clear it
        setViews();                                 // set views 
        setProgressBarIndeterminateVisibility(true);
        sdcardImages.setAdapter(imageAdapter);      // Fill adapter 
        loadImages();                               // Load images from default gallery 

    }


    /**
     * Free up bitmap related resources.
     */

    protected void onDestroy() {
        super.onDestroy();
        final GridView grid = sdcardImages;
        final int count = grid.getChildCount();
        ImageView v = null;
        for (int i = 0; i < count; i++) {
            v = (ImageView) grid.getChildAt(i);
            ((BitmapDrawable) v.getDrawable()).setCallback(null);
        }
    }





    /**
     * Load images...
     */
    private void loadImages() {

        final Object data = getLastNonConfigurationInstance();

        if (data == null) {

            new LoadImagesFromSDCard().execute();
        } else {

            final LoadedImage[] photos = (LoadedImage[]) data;
            if (photos.length == 0) {
                new LoadImagesFromSDCard().execute();
            }
            for (LoadedImage photo : photos) {
                addImage(photo);
            }
        }
    }





    /**
     * Load images from SD Card in the background, and display each image on the
     * screen.
     * 
     * @see android.os.AsyncTask#doInBackground(Params[])
     */

    private class LoadImagesFromSDCard extends
            AsyncTask<Object, LoadedImage, Object> {

        @Override
        protected Object doInBackground(Object... params) {

               Uri uri = null;      
               Bitmap bitmap = null;
               Bitmap newBitmap = null;




              String[] projection = {MediaStore.Images.Thumbnails._ID};

              Cursor cursor = managedQuery( MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI,
                        projection, // Which columns to return
                        null,       // Return all rows
                        null,       
                        null); 


              int columnIndex = cursor.getColumnIndexOrThrow(MediaStore.Images.Thumbnails._ID);
              int size = cursor.getCount();
               int imageID = 0;

              for (int i = 0; i < size; i++) {
                    cursor.moveToPosition(i);
                    imageID = cursor.getInt(columnIndex);
                    uri = Uri.withAppendedPath(MediaStore.Images.Thumbnails.EXTERNAL_CONTENT_URI, "" + imageID);
                    try {
                        bitmap = BitmapFactory.decodeStream(getContentResolver().openInputStream(uri));
                        if (bitmap != null) {
                            newBitmap = Bitmap.createScaledBitmap(bitmap, 70, 70, true);
                            bitmap.recycle();
                            if (newBitmap != null) {
                                publishProgress(new LoadedImage(newBitmap,String.valueOf(imageID)));
                            }
                        }
                    } catch (IOException e) {
                        //Error fetching image, try to recover
                        Log.e(TAG, e.toString());
                    }
                }


            return null;
        }



        /**
         * Add a new LoadedImage in the images grid.
         * 
         * @param value
         *            The image.
         */
        @Override
        public void onProgressUpdate(LoadedImage... value) {
            addImage(value);
        }



        /**
         * Set the visibility of the progress bar to false.
         * 
         * @see android.os.AsyncTask#onPostExecute(java.lang.Object)
         */
        @Override
        protected void onPostExecute(Object result) {
            setProgressBarIndeterminateVisibility(false);
        }
    }

    /**
     * Add image(s) to the grid view adapter.
     * 
     * @param value
     *            Array of LoadedImages references
     */
    private void addImage(LoadedImage... value) {
        for (LoadedImage image : value) {
            imageAdapter.addPhoto(image);
            imageAdapter.notifyDataSetChanged();
        }
    }



    /**
     * Set view function will set views 
     * 
     */

    private void setViews() {

        sdcardImages = (GridView) findViewById(R.id.sdcard);

        sdcardImages.setOnItemLongClickListener(this); // Set Listener on GridView

        imageAdapter = new ImageAdapter(getApplicationContext());

        imageAdapter.notifyDataSetChanged();

    }



/**
 * Function will return bitmap of Gallery big image
 * @param imagePath
 * @return
 */

private Bitmap getImageBitmap(String imagePath) {
    // TODO Auto-generated method stub

    try {
        is = new FileInputStream(new File(imagePath));
        bis = new BufferedInputStream(is);
        bitmap = BitmapFactory.decodeStream(bis);

    } catch (Exception e) {
        // Try to recover
    } finally {
        try {
            if (bis != null) {
                bis.close();
            }
            if (is != null) {
                is.close();
            }

        } catch (Exception e) {
        }
    }

    System.gc();
    return bitmap;

}

/*** 函数将返回从图库中选择的拇指图像* @param thumbImagePath* @返回*/

/** * Function will return thumb image of selected from gallery * @param thumbImagePath * @return */

private Bitmap getThumbnailBitmap(String thumbImagePath) {

        try {
            is = new FileInputStream(new File(thumbImagePath));
            bis = new BufferedInputStream(is);
            bitmap = BitmapFactory.decodeStream(bis);

        } catch (Exception e) {
            // Try to recover
        } finally {
            try {
                if (bis != null) {
                    bis.close();
                }
                if (is != null) {
                    is.close();
                }

            } catch (Exception e) {
            }
        }

        System.gc();
        return bitmap;




    }




    }






    /**
     * This class is used for image adapter
     * @author 
     *
     */
    class ImageAdapter extends BaseAdapter {

        private Context mContext;

        ImageAdapter(Context context) {
            mContext = context;
        }

        public void addPhoto(LoadedImage photo) {
            photos.add(photo);
        }

        public int getCount() {
            return photos.size();
        }

        public Object getItem(int position) {
            return photos.get(position);
        }

        public long getItemId(int position) {
            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            final ImageView imageView;
            if (convertView == null) {
                imageView = new ImageView(mContext);
                imageView.setLayoutParams(new GridView.LayoutParams(90, 90));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            } else {
                imageView = (ImageView) convertView;
            }

            imageView.setImageBitmap(photos.get(position).getImage());

            return imageView;
        }
    }

}

布局:

    <?xml version="1.0" encoding="utf-8"?>
<GridView xmlns:android="http://schemas.android.com/apk/res/android" 
    android:id="@+id/sdcard"
    android:layout_width="fill_parent"


    android:layout_height="fill_parent" android:stretchMode="columnWidth"
        android:gravity="center" android:layout_below="@id/RelativeWallTopBar"
        android:numColumns="auto_fit" android:columnWidth="90dp"
        android:horizontalSpacing="5dip" android:verticalSpacing="15dip" />

这篇关于在我的应用程序中显示画廊的图像的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆