使用URL在ImageView中显示时,从相机捕获的图像缩小

时间:2018-01-21 01:45:46

标签: android android-imageview android-camera-intent

我是android的新手请帮帮我吧。非常感激。问题是,我从相机获取图像,在捕获后,它将通过获取捕获的图像URL显示在Imageview中。但是,当图像显示在Imageview中时,图像不是其实际尺寸,它会显着缩小。请问有人能帮帮我吗。

以下是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);
  }
}

以下是xml文件:

    <?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>

这是SomeView类的代码:

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;
    }
}

链接到发生的事情的图像: Actual image on camera Displayed image in ImageView gets shrink

1 个答案:

答案 0 :(得分:0)

来自相机的小图像表示缩略图,因为您使用了额外的读取位图..

此示例将帮助您获得完整图像:

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