我想从其数据库中检索图库中的所有图像,并希望在我的应用程序中显示在 gridview 中。请告诉怎么做..
问问题
2740 次
2 回答
2
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 * @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" />
于 2012-06-04T06:55:57.740 回答
0
这里我采用了 main.xml,其中包含一个按钮和一个 Imageview。当我按下按钮时,图像会从图库中显示,当我单击图像时,它会显示在图像视图中。
main.java
public class GalleryImagePickActivity extends Activity {
/** Called when the activity is first created. */
private static final int SELECT_PICTURE = 1;
ImageView imgBG;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
imgBG = (ImageView) findViewById(R.id.imgBG);
}
public void btnChooseBGClick(View v) {
Intent i = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(i, SELECT_PICTURE);
}
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode) {
case SELECT_PICTURE:
if (resultCode == RESULT_OK) {
Uri uri = imageReturnedIntent.getData();
String[] projection = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(uri, projection,
null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(projection[0]);
String filePath = cursor.getString(columnIndex);
cursor.close();
Bitmap yourSelectedImage = BitmapFactory.decodeFile(filePath);
Drawable d = new BitmapDrawable(yourSelectedImage);
imgBG.setBackgroundDrawable(d);
}
}
}
}
我希望它对你有帮助。
于 2012-06-04T07:21:53.900 回答