0

I am new to android pls help me with it. Much appreciated. The problem is that, i get the image from camera, after it is being captured it will be display in the Imageview by getting captured image URL. however, when the image is display in the Imageview, the image is not of its actual size, it shrinks significantly. Could anyone help me with it, please.

The following is the code for cameraActivity:

    public class CameraActivity extends AppCompatActivity {

Integer REQUEST_CAMERA =1, GALLERY_KITKAT_INTENT_CALLED=0;
public ImageView capturedPhoto;



@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_camera);

    SelectImage();
    capturedPhoto = (ImageView) findViewById(R.id.cameraPhoto);
}

private void SelectImage()
{
    final CharSequence[] items ={"Camera","Gallery","Cancel"};

    AlertDialog.Builder builder = new AlertDialog.Builder(CameraActivity.this);
    builder.setTitle("Add Image");
    builder.setItems(items, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            if (items[i].equals("Camera")) {

                Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                startActivityForResult(intent, REQUEST_CAMERA);
                //dispatchTakePictureIntent();


            } else if (items[i].equals("Gallery")) {
                Intent intent2 = new Intent(Intent.ACTION_OPEN_DOCUMENT);
                intent2.addCategory(Intent.CATEGORY_OPENABLE);

                intent2.setType("image/*");
                startActivityForResult(intent2, GALLERY_KITKAT_INTENT_CALLED);

            } else if (items[i].equals("Cancel")) {
                dialogInterface.dismiss();
            }
        }
    });
    builder.show();
}
@Override
public void onActivityResult(int requestCode,int resultCode, Intent data)
{
    super.onActivityResult(requestCode,resultCode,data);

    if(resultCode == Activity.RESULT_OK && requestCode == REQUEST_CAMERA)
    {


        Bitmap image =(Bitmap) data.getExtras().get("data");
        capturedPhoto.setImageBitmap(image);

        //call to get uri from bitmap
        Uri tempUri = getImageUri(getApplicationContext(),image);

        //call to get actual path
        //Toast.makeText(CameraActivity.this,"Here"+getRealPathFromURI(tempUri),Toast.LENGTH_SHORT).show();
        GlobalVariables.filepath=getRealPathFromURI(tempUri);
        setContentView(new SomeView(CameraActivity.this));

    }


    if (requestCode == GALLERY_KITKAT_INTENT_CALLED && resultCode == RESULT_OK && null != data )
    {
        if (requestCode == GALLERY_KITKAT_INTENT_CALLED) {

            String filepath2 = "";
            Uri originalUri = null;
            originalUri = data.getData();

            final int takeFlags = data.getFlags()
                    & (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
            // Check for the freshest data.
            getContentResolver().takePersistableUriPermission(originalUri,
                    takeFlags);
            filepath2 = getPath(originalUri);

            if (filepath2.toString() != null) {
                // LoadPicture(filepath);
                GlobalVariables.filepath = filepath2;
                // cropImageView.setVisibility(View.VISIBLE);
                setContentView(new SomeView(CameraActivity.this));

            }
        }
    }
}

@SuppressLint("NewApi")
private String getPath(Uri uri) {
    if (uri == null) {
        return null;
    }

    String[] projection = {MediaStore.Images.Media.DATA};

    Cursor cursor;
    if (Build.VERSION.SDK_INT > 19) {
        // Will return "image:x*"
        String wholeID = DocumentsContract.getDocumentId(uri);
        // Split at colon, use second item in the array
        String id = wholeID.split(":")[1];
        // where id is equal to
        String sel = MediaStore.Images.Media._ID + "=?";

        cursor = getContentResolver().query(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection,
                sel, new String[]{id}, null);
    } else {
        cursor = getContentResolver().query(uri, projection, null, null,
                null);
    }
    String path = null;
    try {
        int column_index = cursor
                .getColumnIndex(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        path = cursor.getString(column_index).toString();
        cursor.close();
    } catch (NullPointerException e) {

    }
    return path;
}

public Uri getImageUri(Context inContext, Bitmap image )
{
    //ByteArrayOutputStream bytes = new ByteArrayOutputStream();
    //thumbnail.compress(Bitmap.CompressFormat.JPEG,100,bytes);

    String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(),image,"title",null);
    return Uri.parse(path);
}

public String getRealPathFromURI(Uri uri)
{
    Cursor cursor = getContentResolver().query(uri,null,null,null,null);
    cursor.moveToFirst();
    int idx=cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);

    return cursor.getString(idx);
  }
}

The following is the xml file:

    <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.mbdp.w.areametric.CameraActivity">

    <ImageView
        android:id="@+id/cameraPhoto"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

This is the code for SomeView class:

public class SomeView extends View implements View.OnTouchListener{
    private Paint paint;
    public static List<Point> points;
    int DIST = 2;
    boolean flgPathDraw = true;
    String filepath = GlobalVariables.filepath;
    Point mfirstpoint = null;
    boolean bfirstpoint = false;

    Point mlastpoint = null;

    Bitmap bitmap = scaleToActualAspectRatio(rotateBitmap(filepath,
            BitmapFactory.decodeFile(filepath)));
    Context mContext;

    public SomeView(Context c) {
        super(c);

        Toast.makeText(getContext(), "Crop the coin on image", Toast.LENGTH_LONG)
                .show();
        mContext = c;
        setFocusable(true);
        setFocusableInTouchMode(true);

        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.STROKE);
        paint.setPathEffect(new DashPathEffect(new float[]{10, 20}, 0));
        paint.setStrokeWidth(5);
        paint.setColor(Color.WHITE);

        this.setOnTouchListener(this);
        points = new ArrayList<Point>();

        bfirstpoint = false;
    }

    public SomeView(Context context, AttributeSet attrs) {
        super(context, attrs);
        mContext = context;
        setFocusable(true);
        setFocusableInTouchMode(true);

        paint = new Paint(Paint.ANTI_ALIAS_FLAG);
        paint.setStyle(Paint.Style.STROKE);
        paint.setStrokeWidth(2);
        paint.setColor(Color.WHITE);

        this.setOnTouchListener(this);
        points = new ArrayList<Point>();
        bfirstpoint = false;

    }

    public void onDraw(Canvas canvas) {
        canvas.drawBitmap(bitmap, 0, 0, null);

        Path path = new Path();
        boolean first = true;

        for (int i = 0; i < points.size(); i += 2) {
            Point point = points.get(i);
            if (first) {
                first = false;
                path.moveTo(point.x, point.y);
            } else if (i < points.size() - 1) {
                Point next = points.get(i + 1);
                path.quadTo(point.x, point.y, next.x, next.y);
            } else {
                mlastpoint = points.get(i);
                path.lineTo(point.x, point.y);
            }
        }
        canvas.drawPath(path, paint);
    }

    public boolean onTouch(View view, MotionEvent event) {

        Point point = new Point();
        point.x = (int) event.getX();
        point.y = (int) event.getY();

        if (flgPathDraw) {

            if (bfirstpoint) {

                if (comparepoint(mfirstpoint, point)) {
                    // points.add(point);
                    points.add(mfirstpoint);
                    flgPathDraw = false;
                    showcropdialog();
                } else {
                    points.add(point);
                }
            } else {
                points.add(point);
            }

            if (!(bfirstpoint)) {

                mfirstpoint = point;
                bfirstpoint = true;
            }
        }

        invalidate();
        Log.e("Hi  ==>", "Size: " + point.x + " " + point.y);

        if (event.getAction() == MotionEvent.ACTION_UP) {
            Log.d("Action up", "called");
            mlastpoint = point;
            if (flgPathDraw) {
                if (points.size() > 12) {
                    if (!comparepoint(mfirstpoint, mlastpoint)) {
                        flgPathDraw = false;
                        points.add(mfirstpoint);
                        showcropdialog();
                    }
                }
            }
        }

        return true;
    }

    private boolean comparepoint(Point first, Point current) {
        int left_range_x = (int) (current.x - 3);
        int left_range_y = (int) (current.y - 3);

        int right_range_x = (int) (current.x + 3);
        int right_range_y = (int) (current.y + 3);

        if ((left_range_x < first.x && first.x < right_range_x)
                && (left_range_y < first.y && first.y < right_range_y)) {
            if (points.size() < 10) {
                return false;
            } else {
                return true;
            }
        } else {
            return false;
        }

    }

    public void resetView() {
        points.clear();
        paint.setColor(Color.WHITE);
        paint.setStyle(Paint.Style.STROKE);
        flgPathDraw = true;
        invalidate();
    }


    public Bitmap scaleToActualAspectRatio(Bitmap bitmap) {
        if (bitmap != null) {

            boolean flag = true;
            DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
            int deviceWidth = metrics.widthPixels;
            int deviceHeight = metrics.heightPixels;
            Matrix matrix = new Matrix();

            matrix.postRotate(90);

            int bitmapHeight = bitmap.getHeight(); // 563
            int bitmapWidth = bitmap.getWidth(); // 900

            // aSCPECT rATIO IS Always WIDTH x HEIGHT rEMEMMBER 1024 x 768

            if (bitmapWidth > deviceWidth) {
                flag = false;

                // scale According to WIDTH
                int scaledWidth = deviceWidth;
                int scaledHeight = (scaledWidth * bitmapHeight) / bitmapWidth;

                try {
                    if (scaledHeight > deviceHeight)
                        scaledHeight = deviceHeight;

                    bitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth,
                            scaledHeight, true);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }

            if (flag) {
                if (bitmapHeight > deviceHeight) {
                    // scale According to HEIGHT
                    int scaledHeight = deviceHeight;
                    int scaledWidth = (scaledHeight * bitmapWidth)
                            / bitmapHeight;

                    try {
                        if (scaledWidth > deviceWidth)
                            scaledWidth = deviceWidth;

                        bitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth,
                                scaledHeight, true);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
        return bitmap;

    }

    private void showcropdialog() {
        DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                Intent intent;
                switch (which) {

                    case DialogInterface.BUTTON_NEUTRAL:
                        resetView();

                        break;
                    case DialogInterface.BUTTON_POSITIVE:
                        // Yes button clicked
                        // bfirstpoint = false;

                        intent = new Intent(mContext, CropActivity.class);
                        intent.putExtra("crop", true);
                        mContext.startActivity(intent);
                        break;

                    case DialogInterface.BUTTON_NEGATIVE:
                        // No button clicked

                        intent = new Intent(mContext, CropActivity.class);
                        intent.putExtra("crop", false);
                        mContext.startActivity(intent);

                        bfirstpoint = false;
                        // resetView();

                        break;
                }
            }
        };

        AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
        builder.setMessage("Please select Crop or Inverse crop")
                .setNeutralButton("Re-Crop", dialogClickListener)
                .setPositiveButton("Crop", dialogClickListener)
                .setNegativeButton("Inverse Crop", dialogClickListener).show()
                .setCancelable(false);
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        // Handle the back button
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            // Ask the user if they want to quit
            // restart app
            Intent i = getContext().getPackageManager()
                    .getLaunchIntentForPackage(getContext().getPackageName());
            i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
            // startActionMode(i);
            SomeView.this.getContext().startActivity(i);

            return true;
        } else {
            return super.onKeyDown(keyCode, event);
        }
    }

    public static Bitmap rotateBitmap(String src, Bitmap bitmap) {
        try {
            int orientation = getExifOrientation(src);

            if (orientation == 1) {
                return bitmap;
            }

            Matrix matrix = new Matrix();
            switch (orientation) {
                case 2:
                    matrix.setScale(-1, 1);
                    break;
                case 3:
                    matrix.setRotate(180);
                    break;
                case 4:
                    matrix.setRotate(180);
                    matrix.postScale(-1, 1);
                    break;
                case 5:
                    matrix.setRotate(90);
                    matrix.postScale(-1, 1);
                    break;
                case 6:
                    matrix.setRotate(90);
                    break;
                case 7:
                    matrix.setRotate(-90);
                    matrix.postScale(-1, 1);
                    break;
                case 8:
                    matrix.setRotate(-90);
                    break;
                default:
                    return bitmap;
            }

            try {
                Bitmap oriented = Bitmap.createBitmap(bitmap, 0, 0,
                        bitmap.getWidth(), bitmap.getHeight(), matrix, true);
                bitmap.recycle();
                return oriented;
            } catch (OutOfMemoryError e) {
                e.printStackTrace();
                return bitmap;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

        return bitmap;
    }


    private static int getExifOrientation(String src) throws IOException {
        int orientation = 1;

        try {

            if (Build.VERSION.SDK_INT >= 5) {
                Class<?> exifClass = Class
                        .forName("android.media.ExifInterface");
                Constructor<?> exifConstructor = exifClass
                        .getConstructor(new Class[]{String.class});
                Object exifInstance = exifConstructor
                        .newInstance(new Object[]{src});
                Method getAttributeInt = exifClass.getMethod("getAttributeInt",
                        new Class[]{String.class, int.class});
                Field tagOrientationField = exifClass
                        .getField("TAG_ORIENTATION");
                String tagOrientation = (String) tagOrientationField.get(null);
                orientation = (Integer) getAttributeInt.invoke(exifInstance,
                        new Object[]{tagOrientation, 1});
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SecurityException e) {
            e.printStackTrace();
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        } catch (NoSuchFieldException e) {
            e.printStackTrace();
        }

        return orientation;
    }
}

Links to image of what happened: Actual image on camera Displayed image in ImageView gets shrink

Alex Cohn
  • 56,089
  • 9
  • 113
  • 307
awa
  • 19
  • 1
  • 7

1 Answers1

0

That small image from camera indicates thumbnail since you use reading bitmap from extra..

This example will help you get full image:  

How to capture an image and store it with the native Android Camera

Alex Cohn
  • 56,089
  • 9
  • 113
  • 307
Pratim P
  • 169
  • 1
  • 5