-1

I am a new bee in Android development. With the help of one of the developers in this stackoverflow community I resolved image landscape issue and left with 2 more issues to complete my project.

  1. Crop image before setting it as imageview's background.
  2. How to stop imageview from shrinking even though keeping ImageView.ScaleType.FIT_XY ,.I mean the image I select from gallery should occupy the whole screen(layout) without shrinking. I have gone through some of the questions and answers in this site regarding the same but didnt find them fitting exactly my code.

1.Crop an image from gallery in android

2.android:select image from gallery then crop that and show in an imageview

Here is the source code of my fragment:

public class FragmentTab1 extends Fragment {
    RelativeLayout homes;
    private static int RESULT_LOAD_IMAGE = 1;
    ImageView bitmapView;
    BitmapFactory.Options options;
    String filePath;
    Button rot;
    private int mDegree = 0;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragmenttab1, container, false);
        homes = (RelativeLayout) view.findViewById(R.id.hmt);
        homes.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Intent i = new Intent(
                        Intent.ACTION_PICK,
                        android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                startActivityForResult(i, RESULT_LOAD_IMAGE);
            }
        });
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getActivity());
        final String filePath = prefs.getString("profilePic", "");
        if (!filePath.equals("")) {
            bitmapView = (ImageView) view.findViewById(R.id.keka);
            bitmapView.setImageBitmap(ExifUtils.rotateBitmap(filePath, decodeSampledBitmap(new File(filePath), 400, 400)));
            bitmapView.setScaleType(ImageView.ScaleType.FIT_XY);

        }

        return view;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == RESULT_LOAD_IMAGE && resultCode == getActivity().RESULT_OK && null != data) {
            Uri picUri = data.getData();
            String[] filePathColumn = {MediaStore.Images.Media.DATA};
            Cursor cursor = getActivity().getContentResolver().query(picUri,
                    filePathColumn, null, null, null);
            cursor.moveToFirst();
            int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
            filePath = cursor.getString(columnIndex);
            cursor.close();
            bitmapView = (ImageView) getActivity().findViewById(R.id.keka);
            bitmapView.setImageBitmap(ExifUtils.rotateBitmap(filePath, decodeSampledBitmap(new File(filePath), 400, 400)));
            bitmapView.setScaleType(ImageView.ScaleType.FIT_XY);
            SharedPreferences shre = PreferenceManager.getDefaultSharedPreferences(getActivity());
            Editor edit = shre.edit();
            edit.putString("profilePic", filePath);
            edit.commit();
        }
    }
    public Bitmap decodeSampledBitmap(File res, int reqWidth, int reqHeight) {
        if (res != null) {
            // First decode with inJustDecodeBounds=true to check dimensions
            final BitmapFactory.Options options = new BitmapFactory.Options();
            options.inJustDecodeBounds = true;
            try {
                FileInputStream stream2 = new FileInputStream(res);

                BitmapFactory.decodeStream(stream2, null, options);

                stream2.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // Calculate inSampleSize
            BitmapFactory.Options o2 = new BitmapFactory.Options();
            o2.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
            o2.inJustDecodeBounds = false;
            FileInputStream stream = null;
            try {
                stream = new FileInputStream(res);
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            }
            Bitmap bitmap = BitmapFactory.decodeStream(stream, null, o2);
            try {
                stream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            return bitmap;
        } else
            return null;
    }

    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) {

            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;
    }`enter code here`
}`enter code here`
Community
  • 1
  • 1
Adithya
  • 183
  • 1
  • 2
  • 16

1 Answers1

-1

I would recommend to crop the image in an image editor first, then set the image as your ImageView's background in the XML layout file like in this example:

   <ImageView>   
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/yourCroppedImage"/>

You shouldn't need to add any additional scale attributes or properties.

An alternative solution is to set the cropped image as the background for your entire layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                xmlns:tools="http://schemas.android.com/tools"
                android:layout_width="fill_parent"
                android:layout_height="fill_parent"
                tools:context=".MainActivity"
                android:background="@drawable/yourCroppedImage">
joshgoldeneagle
  • 4,616
  • 2
  • 23
  • 30
  • Hi Josh, thanks for your answer, but will this logic crops the images from gallery and automatically sets as imageview bacground.Thanks. – Adithya Aug 20 '15 at 05:16
  • You should not use Android Studio to crop your images, but rather crop your images ahead of time in an image editor. Any kind of automatic cropping that would be done in Android will have unpredictable results depending on what device you are using to view your app. You may want to use separate images for landscape layouts (for landscape oriented devices such as tablets) as well. – joshgoldeneagle Aug 20 '15 at 19:08