Swipe large images with no delay - android

I developed a gallery app with swipe images function (drag to the left/right and a new full screen image is appear).
The problem is that I did not succeed to overcome the small delay of large images until they appear (whatsapp images - no problem, with camera images it is not smooth like in the build-in gallery app).
I tried several method to re size/decode the image but still there is a delay.
My code:
FullScreenImageAdapter.java
public class FullScreenImageAdapter extends PagerAdapter {
private Activity _activity;
private ArrayList<String> _imagePaths;
private LayoutInflater inflater;
private final int IMAGE_MAX_SIZE = 800;
// constructor
public FullScreenImageAdapter(Activity activity,
ArrayList<String> imagePaths) {
this._activity = activity;
this._imagePaths = imagePaths;
}
#Override
public int getCount() {
return this._imagePaths.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((RelativeLayout) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imgDisplay;
inflater = (LayoutInflater) _activity
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View viewLayout = inflater.inflate(R.layout.layout_fullscreen_image, container,
false);
imgDisplay = (ImageView) viewLayout.findViewById(R.id.imgDisplay);
Bitmap bitmap = decodeSampledBitmapFromPath(_imagePaths.get(position),1000,1000);
imgDisplay.setImageBitmap(bitmap);
((ViewPager) container).addView(viewLayout);
return viewLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((RelativeLayout) object);
}
public static Bitmap decodeSampledBitmapFromPath(String path, int reqWidth,
int reqHeight) {
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bmp = BitmapFactory.decodeFile(path, options);
return bmp;
}
public static int calculateInSampleSize(BitmapFactory.Options options,
int reqWidth, int reqHeight) {
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height / (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
}
FullScreenViewActivity.java
public class FullScreenViewActivity extends Activity{
private FullScreenImageAdapter adapter;
private ViewPager viewPager;
int selectedFilePosition;
String imageFolder;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_screen_view);
//geting the selected image from the intent
/* Getting ImageURI from Gallery from Main Activity */
Uri selectedImgUri = getIntent().getData();
if (selectedImgUri!=null) {
imageFolder = getRealPathFromURI(this, selectedImgUri);
}
viewPager = (ViewPager) findViewById(R.id.pager);
adapter = new FullScreenImageAdapter(FullScreenViewActivity.this, getFilePaths(imageFolder));
viewPager.setAdapter(adapter);
// displaying selected image first
viewPager.setCurrentItem(selectedFilePosition);
}
// Reading file paths from SDCard
public ArrayList<String> getFilePaths(String selectedFilePath) {
ArrayList<String> filePaths = new ArrayList<String>();
File file = new File(selectedFilePath);
File directory = file.getParentFile();
// check for directory
if (directory.isDirectory()) {
// getting list of file paths
File[] listFiles = directory.listFiles();
// Check for count
if (listFiles.length > 0) {
// loop through all files
for (int i = 0; i < listFiles.length; i++) {
// get file path
String filePath = listFiles[i].getAbsolutePath();
//set position if this is the required image to show
if (filePath.equals(selectedFilePath)) {
selectedFilePosition = i;
// Add image path to array list
filePaths.add(filePath);
}
}
}
}
return filePaths;
}
public String getRealPathFromURI(Context context, Uri contentUri) {
Cursor cursor = null;
try {
String[] proj = { MediaStore.Images.Media.DATA };
cursor = context.getContentResolver().query(contentUri, proj, null, null, null);
int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
} finally {
if (cursor != null) {
cursor.close();
}
}
}
}

To improve performance you need another thread to load it async. Here are the third party libraries (Picasso, Glide) that you can use when working with large images.

I also would use Picasso for loading Images into the ImageView. Picasso caches the Image if it is Loaded once. To preload some elements you can use the Consumner/Producer Pattern! Example here.

Related

how to show all photos using AsyncTask

I want to collect all photos in pictures directory to show them in GridView, so tried with two ways.
1_ without using AsyncTask: this way worked very well but it has a problem which is that the app freezes for seconds to get all photos in specified directory and it's sub directories.
2_using AsyncTask: this way doesn't get any images and the list of images is always empty, I know that I should use Asynctask for processes that take mush time to processed and I don't know what I missed when using AsyncTask.
what I want is to find a way to collect all photos using AsyncTask with app freezing and thanks in advance.
public static class ImagesFragment extends Fragment {
static List<Image> imagesList = new ArrayList<>();
GridViewRecyclerAdapter gridViewRecyclerAdapter;
GridView gridView;
Spinner spinner;
public static File file = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// imagesList = loadImageData(file);
gridViewRecyclerAdapter = new GridViewRecyclerAdapter(imagesList, getContext());
}
#Nullable
#Override
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_images, container, false);
spinner = view.findViewById(R.id.spinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(getContext(), R.array.spinner, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
spinner.setAdapter(adapter);
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
#Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
switch (position){
case 0:
break;
case 1:
break;
}
}
#Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
gridView = view.findViewById(R.id.grid_view);
gridView.setAdapter(gridViewRecyclerAdapter);
return view;
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) >= reqHeight && (halfWidth / inSampleSize) >= reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public static List<Image> loadImageData(File file) {
String fileType;
String extension;
if(file.isDirectory()){
File[] files = file.listFiles();
for(File file1: files){
if(file1.isDirectory())
loadImageData(file1);
else{
extension = MimeTypeMap.getFileExtensionFromUrl(file1.getPath());
if (extension != null) {
fileType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
if(fileType != null)
if(fileType.contains("image")){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = calculateInSampleSize(options, 500, 500);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(file1.getAbsolutePath(), options);
// bitmap = Bitmap.createScaledBitmap(bitmap, bitmap.getWidth(), bitmap.getHeight())
imagesList.add(new Image(bitmap, file1.getName(), file1.getPath()));
}
}
}
}
}
else {
extension = MimeTypeMap.getFileExtensionFromUrl(file.getPath());
if (extension != null) {
fileType = MimeTypeMap.getSingleton().getMimeTypeFromExtension(extension);
if(fileType != null)
if(fileType.contains("image")){
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = calculateInSampleSize(options, 500, 500);
options.inJustDecodeBounds = false;
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath(), options);
imagesList.add(new Image(bitmap, file.getName(), file.getPath()));
}
}
}
return imagesList;
}
}
public static class GridViewRecyclerAdapter extends BaseAdapter {
List<Image> imageList;
Context context;
static int position;
public GridViewRecyclerAdapter(List<Image> imageList, Context context){
this.imageList = imageList;
this.context = context;
}
#Override
public int getCount() {
return imageList.size();
}
#Override
public Object getItem(int position) {
return imageList.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if(convertView == null){
convertView = LayoutInflater.from(context).inflate(R.layout.images_item, parent, false);
viewHolder = new ViewHolder();
viewHolder.imageView = convertView.findViewById(R.id.image_view);
viewHolder.imageView.setTag(imageList.get(position).path);
viewHolder.textView = convertView.findViewById(R.id.text_view);
convertView.setTag(viewHolder);
}
else
viewHolder = (ViewHolder) convertView.getTag();
new LoadImageAsyncTask().execute(ImagesFragment.file.getAbsolutePath());
viewHolder.imageView.setImageBitmap(imageList.get(position).bitmap);
viewHolder.textView.setText(imageList.get(position).title);
GridViewRecyclerAdapter.position = position;
return convertView;
}
public static class ViewHolder{
ImageView imageView;
TextView textView;
}
static class LoadImageAsyncTask extends AsyncTask<String, Void, List<Image>> {
#Override
protected List<Image> doInBackground(String... objects) {
ImagesFragment.imagesList = ImagesFragment.loadImageData(new File(objects[0]));
return ImagesFragment.imagesList;
}
}
}

I can't able to take my Images to new activity that are loaded from SD card

Image activity
public class ImageAdapter extends BaseAdapter {
private Context context;
Bitmap bm;
ArrayList<String>images = new ArrayList<String>();
// Integer[] images;
void add(String path) {
images.add(path);
}
public ImageAdapter(Context c) {
context = c;
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object getItem(int position) {
return images;
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(context);
if (convertView == null) {
// imageView.setImageResource(images[position]);
// imageView.setImageBitmap(images);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setLayoutParams(new GridView.LayoutParams(240, 240));
return imageView;
} else {
imageView = (ImageView) convertView;
}
bm = decodeSampledBitmapFromUri(images.get(position), 220, 220);
imageView.setImageBitmap(bm);
return imageView;
}
private Bitmap decodeSampledBitmapFromUri(String path, int reqWidth, int reqHeight) {
Bitmap bm = null;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(path, options);
return bm;
}
public int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float)height / (float)reqHeight);
} else {
inSampleSize = Math.round((float)width / (float)reqWidth);
}
}
return inSampleSize;
}
}
Main Activity
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Intent i= new Intent(getApplicationContext(), FullImageActivity.class);
i.putExtra("id", position);
startActivity(i);
}
});
FullImageActivity
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_image);
Intent i=getIntent();
int position= i.getExtras().getInt("id");
ImageAdapter imageAdapter= new ImageAdapter(this);
ImageView imageView=(ImageView)findViewById(R.id.imageView);
imageView.setImageBitmap(imageAdapter.bm); \\here I have to show my images that are read from Storage
}
I can't able to pass it properly because my arraylist are string. I tried many ways that I know but that not work properly. I tried from internet also but not working.
I can't show my images through fullimage activity. I read images from SD card so It not showing in full view. Thanks in advance
Your code is not executing properly because it is not setup correctly.
First thing's first, consider using Picasso or Glide or UniversalImageLoader for loading your images into the placeholders to avoid making a clunky user experience scrolling through images.
Secondly, passing the position to the second activity is not your goal. You are trying to pass the image. So pass the image lol,
First on your getItem()
you should return the individual image based on position images.get(position)
rather then return images.
Secondly in your click handler
Either pass it as an extra like
intent.addExtra(myAdapter.getItem(position))
or if you have the list already just do
intent.addExtra(myList.get(position))
or simply cheat with ActivityTwo.imageToShow = myList.get(position)
startActivityTwo
anyone of these will work fine.

Android: ClickListener to view full size thumbnail .jpeg from a gridview

I'm new to android and have been working with a tutorial which loads all images from a directory on the SD card. I have the tutorial running but would like to add some code to the click listener which will load a full size version of the thumbnail in the gridview image adapter.
public class PicturesFragment extends Fragment {
public class ImageAdapter extends BaseAdapter {
private Context mContext;
ArrayList<String> itemList = new ArrayList<String>();
public ImageAdapter(Context c) {
mContext = c;
}
void add(String path) {
itemList.add(path);
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return itemList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some
// attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(225, 225));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(1, 1, 1, 1);
} else {
imageView = (ImageView) convertView;
}
Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 220,
220);
imageView.setImageBitmap(bm);
return imageView;
}
public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth,
int reqHeight) {
Bitmap bm = null;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(path, options);
return bm;
}
public int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height
/ (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
}
ImageAdapter myImageAdapter;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.pictures_fragment, container, false);
GridView gridview = (GridView) rootView.findViewById(R.id.gridview);
myImageAdapter = new ImageAdapter(getActivity());
gridview.setAdapter(myImageAdapter);
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory().getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/myfilepath/Images";
Toast.makeText(getActivity().getApplicationContext(), targetPath, Toast.LENGTH_LONG)
.show();
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files) {
myImageAdapter.add(file.getAbsolutePath());
}
gridview.setOnItemClickListener(myOnItemClickListener);
Button camerabtn = (Button) rootView.findViewById(R.id.camerabtn);
camerabtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent(v.getContext(), CameraActivity.class);
startActivityForResult(intent, 0);
}
});
return rootView;
}
Here's the click listener where I believe I should be implementing the code to solve this problem. I think I should be launching another activity (FullImageActivity.class) which just contains a layout with an imageview and pass the image which has been clicked to this new activity , but I have little know how to go about this
OnItemClickListener myOnItemClickListener = new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String prompt = (String) parent.getItemAtPosition(position);
Toast.makeText(getActivity().getApplicationContext(), prompt, Toast.LENGTH_LONG)
.show();
//Intent i = new Intent(getActivity().getApplicationContext(), FullImageActivity.class);
// startActivity(i);
}
};
}
Any help would be greatly appreciated.
Yes, change the onItemClick like this..
#Override
public void onItemClick(AdapterView<?> parent, View view, int position,
long id) {
String path = (String) myImageAdapter.getItem(position);
Intent intent = new Intent(this, FullImageActivity.class);
intent.putExtra("IMAGEPATH",path);
startActivity(intent);
}
And in FullImageActivity have a layout to show the full image from the path.
you can get the path in the FullImageActivity onCreate()
public class FullImageActivity extends ActionBarActivity{
#Override
public void onCreate(Bundle bundle){
super.onCreate(bundle);
setContentView(R.layout.image_layout);
String path = getIntent().getStringExtra("IMAGEPATH");
// load the image from the path and set it to the imageview in layout
}
}

Loading images from assets

i have been working on wallpaper app for a while and it's almost done but the size of app is pretty big cause i use .png extension so currently i'm trying to load jpg via assets instead of png in res
i tried to implement this answer
Images from Assets folder in a GridView
i get an error while loading the imageadapter
02-21 23:13:05.883: E/AndroidRuntime(17634): FATAL EXCEPTION: main
02-21 23:13:05.883: E/AndroidRuntime(17634): java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.imagieview05/com.example.imagieview05.MainActivity}: java.lang.NullPointerException
here is my code
public class MainActivity extends Activity {
private GridView mGridView;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGridView = (GridView) findViewById(R.id.GridView1);
Bitmap[] mBitArray = new Bitmap[4];
try {
mBitArray[0] = getBitmapFromAssets("g1p2.jpg");
mBitArray[1] = getBitmapFromAssets("g1p1.jpg");
mBitArray[2] = getBitmapFromAssets("g1p3.jpg");
mBitArray[3] = getBitmapFromAssets("g1p4.jpg");
} catch (Exception e) {
e.printStackTrace();
}
mGridView.setAdapter(new ImageAdapter(this ,mBitArray));
}
public Bitmap getBitmapFromAssets (String filename) throws IOException{
AssetManager assetManager = getAssets();
InputStream istr = assetManager.open(filename);
Bitmap bitmap = BitmapFactory.decodeStream(istr);
return bitmap;
}
public class ImageAdapter extends BaseAdapter{
private Context mContext;
private Bitmap[] mImageArray;
public GallaryAdapter(Context c, Bitmap[] mBitArray) {
c = mContext;
mBitArray = mImageArray;
}
public int getCount() {
return mImageArray.length;
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return mImageArray[position];
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imgView = new ImageView(mContext);
imgView.setImageBitmap(mImageArray[position]);
//put black borders around the image
imgView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imgView.setLayoutParams(new GridView.LayoutParams(120, 120));
return imgView;
}
here is the original working code without Assets reference
public class MainActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridView = (GridView) findViewById(R.id.GridView1);
gridView.setAdapter(new ImageAdapter(this));
public class ImageAdapter extends BaseAdapter {
private Context mContext;
public ImageAdapter(Context c) {
mContext = c;
}
public int getCount() {
return mThumbIds.length;
}
public Object getItem(int position) {
return null;
}
public long getItemId(int position) {
return 0;
}
// create a new ImageView for each item referenced by the Adapter
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(150, 150));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
imageView.setImageResource(mThumbIds[position]);
return imageView;
}
// references to our images
private Integer[] mThumbIds = {
R.drawable.g1p1, R.drawable.g1p2,
R.drawable.g1p3, R.drawable.g1p4,
R.drawable.g1p5, R.drawable.g1p6,
R.drawable.g1p22, R.drawable.g1p33,
R.drawable.g1p44, R.drawable.g1p55,
R.drawable.g1p5, R.drawable.g1p6,
R.drawable.g1p22, R.drawable.g1p33,
R.drawable.g1p44, R.drawable.g1p55
};
};
thanks for help in advance
mBitArray = mImageArray; its pointing mBitArray toward mImageArray witch is nothing, maybe?
i dont think it really matters if you use jpeg or png memory wise anyway, in the program its going to completely uncompress the jpeg anyway
I wrote the code loader images from assets folder following the example code
private Bitmap decodeStreamFromAssets(String path, int reqWidth, int reqHeight) {
InputStream ims = null;
try {
ims = getAssets().open(path);
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(ims, null, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeStream(ims, null, options);
}
catch (IOException e) {
e.printStackTrace();
}
finally {
if (ims != null) {
try {
ims.close();
}
catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
private int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
// Calculate the largest inSampleSize value that is a power of 2 and keeps both
// height and width larger than the requested height and width.
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
Load *.jpg work, but *.png not work for ex.
IMG // work
Bitmap bitmap = decodeStreamFromAssets("test.jpg", 64, 64);
if(bitmap1 != null){
imageViewTest.setImageBitmap(bitmap);
}
else {
Log.e("ERROR", "error");
}
PNG // not work ( is error )
Bitmap bitmap = decodeStreamFromAssets("test.png", 64, 64);
if(bitmap1 != null){
imageViewTest.setImageBitmap(bitmap);
}
else {
Log.e("ERROR", "error");
}

How can I show the full size of Image?

I'm new here and new in programming Android. I found this example (below is the example) on a site in internet, It's a great tutorial! What do I want to achieve is when once I clicked a picture on the GridView I want to show the full size of the Image.
public class MainActivity extends Activity {
public class ImageAdapter extends BaseAdapter {
private Context mContext;
ArrayList<String> itemList = new ArrayList<String>();
public ImageAdapter(Context c) {
mContext = c;
}
void add(String path) {
itemList.add(path);
}
#Override
public int getCount() {
return itemList.size();
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView;
if (convertView == null) { // if it's not recycled, initialize some
// attributes
imageView = new ImageView(mContext);
imageView.setLayoutParams(new GridView.LayoutParams(220, 220));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setPadding(8, 8, 8, 8);
} else {
imageView = (ImageView) convertView;
}
Bitmap bm = decodeSampledBitmapFromUri(itemList.get(position), 220,
220);
imageView.setImageBitmap(bm);
return imageView;
}
public Bitmap decodeSampledBitmapFromUri(String path, int reqWidth,
int reqHeight) {
Bitmap bm = null;
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
bm = BitmapFactory.decodeFile(path, options);
return bm;
}
public int calculateInSampleSize(
BitmapFactory.Options options, int reqWidth, int reqHeight) {
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth) {
if (width > height) {
inSampleSize = Math.round((float) height
/ (float) reqHeight);
} else {
inSampleSize = Math.round((float) width / (float) reqWidth);
}
}
return inSampleSize;
}
}
ImageAdapter myImageAdapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
GridView gridview = (GridView) findViewById(R.id.gridview);
myImageAdapter = new ImageAdapter(this);
gridview.setAdapter(myImageAdapter);
String ExternalStorageDirectoryPath = Environment
.getExternalStorageDirectory().getAbsolutePath();
String targetPath = ExternalStorageDirectoryPath + "/test/";
Toast.makeText(getApplicationContext(), targetPath, Toast.LENGTH_LONG)
.show();
File targetDirector = new File(targetPath);
File[] files = targetDirector.listFiles();
for (File file : files) {
myImageAdapter.add(file.getAbsolutePath());
}
}
}
Pass the image to the other activity to show it in full view.
To pass the image from Your main Activity. USe following code:
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
ImageView img = ia.getView(position, v, parent);
img.buildDrawingCache();
Bitmap bmap = img.getDrawingCache();
Intent intent = new Intent(HelloGridView.this,
Imageviewer.class);
Bundle bundle = new Bundle();
//bundle.putParcelable("image", bmap);
String par=myimageadpter.getpath(position);
bundle.putParcelable("imagepath", par);
intent.putExtras(bundle);
startActivityForResult(intent, 0);
}
});
In other activity use this code to show the passed image:
Bundle bundle = this.getIntent().getExtras();
bmp=bundle.getParcelable("image");
ImageView img=(ImageView) findViewById(R.id.imageView1);
d =new BitmapDrawable(bmp);
img.setImageBitmap(bmp);
If you pass path. the second activity look like this:
Bundle bundle = this.getIntent().getExtras();
String s=bundle.getParcelable("imagepath");
Bitmap Imagefrompath = BitmapFactory.decodeFile(s);
ImageView img=(ImageView) findViewById(R.id.imageView1);
img.setImageBitmap(Imagefrompath );

Categories

Resources