如何裁剪图像并将其存储在gridview中?

时间:2022-11-05 00:22:00

i am building a app in which user can capture image from camera and then edit that image and store / display the image in a gridview.the problem i am facing is that when the user capture the image instead of crop the image it directly display it in gridview . i need help in this thanks in advance this is my code

我正在构建一个应用程序,用户可以从相机中捕获图像,然后编辑该图像并在gridview中存储/显示图像。我面临的问题是,当用户捕获图像而不是裁剪图像时,它直接显示它在gridview中。我需要帮助,在这之前,这是我的代码

public class MainActivity extends Activity implements OnClickListener {

Button captureBtn = null;
final int CAMERA_CAPTURE = 1;
private Uri picUri;
private DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
private GridView grid;
private  List<String> listOfImagesPath;
Intent CropIntent;
public static final String GridViewDemo_ImagePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/GridViewDemo/";

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

    captureBtn = (Button)findViewById(R.id.capture_btn1);
    captureBtn.setOnClickListener(this);
    grid = ( GridView) findViewById(R.id.gridviewimg);

    listOfImagesPath = null;
    listOfImagesPath = RetriveCapturedImagePath();
    if(listOfImagesPath!=null){
        grid.setAdapter(new ImageListAdapter(this,listOfImagesPath));
    }
}
public void ImageCropFunction() {

    // Image Crop Code
    try {
        CropIntent = new Intent("com.android.camera.action.CROP");

        CropIntent.setDataAndType(picUri, "image/*");

        CropIntent.putExtra("crop", "true");
        CropIntent.putExtra("outputX", 180);
        CropIntent.putExtra("outputY", 180);
        CropIntent.putExtra("aspectX", 3);
        CropIntent.putExtra("aspectY", 4);
        CropIntent.putExtra("scaleUpIfNeeded", true);
        CropIntent.putExtra("return-data", true);

        startActivityForResult(CropIntent, 1);

    } catch (ActivityNotFoundException e) {

    }
}
//Image Crop Code End Here


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.menu, menu);
    return true;
}

@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
    if (arg0.getId() == R.id.capture_btn1) {

        try {
//use standard intent to capture an image
            Intent captureIntent = new 
Intent(MediaStore.ACTION_IMAGE_CAPTURE);
//we will handle the returned data in onActivityResult
            startActivityForResult(captureIntent, CAMERA_CAPTURE);
        } catch(ActivityNotFoundException anfe){
//display an error message
            String errorMessage = "Whoops - your device doesn't support 
capturing images!";
            Toast toast = Toast.makeText(this, errorMessage, 
Toast.LENGTH_SHORT);
            toast.show();
        }
    }

}

protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode == RESULT_OK) {

//user is returning from capturing an image using the camera
        if(requestCode == CAMERA_CAPTURE){
            ImageCropFunction();
            Bundle extras = data.getExtras();
            Bitmap thePic = extras.getParcelable("data");
            String imgcurTime = dateFormat.format(new Date());
            File imageDirectory = new File(GridViewDemo_ImagePath);
            imageDirectory.mkdirs();
            String _path = GridViewDemo_ImagePath + imgcurTime+".jpg";
            try {
                FileOutputStream out = new FileOutputStream(_path);
                thePic.compress(Bitmap.CompressFormat.JPEG, 90, out);
                out.close();
            } catch (FileNotFoundException e) {
                e.getMessage();
            } catch (IOException e) {
                e.printStackTrace();
            }
            listOfImagesPath = null;
            listOfImagesPath = RetriveCapturedImagePath();
            if(listOfImagesPath!=null){
                grid.setAdapter(new ImageListAdapter(this,listOfImagesPath));
            }

        }
    }
}

private List<String> RetriveCapturedImagePath() {
    List<String> tFileList = new ArrayList<String>();
    File f = new File(GridViewDemo_ImagePath);
    if (f.exists()) {
        File[] files=f.listFiles();
        Arrays.sort(files);

        for(int i=0; i<files.length; i++){
            File file = files[i];
            if(file.isDirectory())
                continue;
            tFileList.add(file.getPath());
        }
    }
    return tFileList;
}

public class ImageListAdapter extends BaseAdapter
{
    private Context context;
    private List<String> imgPic;
    public ImageListAdapter(Context c, List<String> thePic)
    {
        context = c;
        imgPic = thePic;
    }
    public int getCount() {
        if(imgPic != null)
            return imgPic.size();
        else
            return 0;
    }

    //---returns the ID of an item---
    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    //---returns an ImageView view---
    public View getView(int position, View convertView, ViewGroup parent)
    {
        ImageView imageView;
        BitmapFactory.Options bfOptions=new BitmapFactory.Options();
        bfOptions.inDither=false;                     //Disable Dithering mode
        bfOptions.inPurgeable=true;                   //Tell to gc that whether it needs free memory, the Bitmap can be cleared
        bfOptions.inInputShareable=true;              //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
        bfOptions.inTempStorage=new byte[32 * 1024];
        if (convertView == null) {
            imageView = new ImageView(context);
            imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
            imageView.setPadding(0, 0, 0, 0);
        } else {
            imageView = (ImageView) convertView;
        }
        FileInputStream fs = null;
        Bitmap bm;
        try {
            fs = new FileInputStream(new File(imgPic.get(position).toString()));

            if(fs!=null) {
                bm=BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions);
                imageView.setImageBitmap(bm);
                imageView.setId(position);
                imageView.setLayoutParams(new GridView.LayoutParams(200, 160));
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally{
            if(fs!=null) {
                try {
                    fs.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
        return imageView;
    }
}
}

2 个解决方案

#1


0  

Let me know if it works

如果有效,请告诉我

first of all change

首先是改变

startActivityForResult(CropIntent, 1); 

to

`startActivityForResult(CropIntent, 2);`

and add to onActivityResult add this:

并添加到onActivityResult添加此:

picUri = Uri.parse(_path);

after that in your onActivityResult remove

之后在你的onActivityResult中删除

listOfImagesPath = null;
            listOfImagesPath = RetriveCapturedImagePath();
            if(listOfImagesPath!=null){
                grid.setAdapter(new ImageListAdapter(this,listOfImagesPath));
            }

and add new result like

并添加新的结果,如

if(requestCode == CAMERA_CAPTURE){
....
} else if(requestCode == 2){
..
 }

and last step in your new statement add this line:

并在新语句的最后一步添加以下行:

else if(requestCode == 2){
listOfImagesPath = null;
            listOfImagesPath = RetriveCapturedImagePath();
            if(listOfImagesPath!=null){
                grid.setAdapter(new ImageListAdapter(this,listOfImagesPath));
            }
}

#2


0  

https://github.com/ArthurHub/Android-Image-Cropper Use this library. It's very easy to use

https://github.com/ArthurHub/Android-Image-Cropper使用此库。它非常易于使用

#1


0  

Let me know if it works

如果有效,请告诉我

first of all change

首先是改变

startActivityForResult(CropIntent, 1); 

to

`startActivityForResult(CropIntent, 2);`

and add to onActivityResult add this:

并添加到onActivityResult添加此:

picUri = Uri.parse(_path);

after that in your onActivityResult remove

之后在你的onActivityResult中删除

listOfImagesPath = null;
            listOfImagesPath = RetriveCapturedImagePath();
            if(listOfImagesPath!=null){
                grid.setAdapter(new ImageListAdapter(this,listOfImagesPath));
            }

and add new result like

并添加新的结果,如

if(requestCode == CAMERA_CAPTURE){
....
} else if(requestCode == 2){
..
 }

and last step in your new statement add this line:

并在新语句的最后一步添加以下行:

else if(requestCode == 2){
listOfImagesPath = null;
            listOfImagesPath = RetriveCapturedImagePath();
            if(listOfImagesPath!=null){
                grid.setAdapter(new ImageListAdapter(this,listOfImagesPath));
            }
}

#2


0  

https://github.com/ArthurHub/Android-Image-Cropper Use this library. It's very easy to use

https://github.com/ArthurHub/Android-Image-Cropper使用此库。它非常易于使用