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

Posted

技术标签:

【中文标题】如何裁剪图像并将其存储在 gridview 中?【英文标题】:how can i crop the image and store it in gridview? 【发布时间】:2017-11-10 18:50:30 【问题描述】:

我正在构建一个应用程序,用户可以在其中从相机捕获图像,然后编辑该图像并在网格视图中存储/显示图像。我面临的问题是当用户捕获图像而不是裁剪图像时直接在 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;
    


【问题讨论】:

【参考方案1】:

让我知道它是否有效

首先改变

startActivityForResult(CropIntent, 1); 

`startActivityForResult(CropIntent, 2);`

并添加到 onActivityResult 添加:

picUri = Uri.parse(_path);

之后在您的 onActivityResult 中删除

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

并添加新结果,如

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

在你的新语句的最后一步添加这一行:

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

【讨论】:

实际上我不想从中心裁剪图像。我想在任何我想要的地方裁剪图像 你能帮我解决这个问题吗 你可以试试这个。但是在String _path = GridViewDemo_ImagePath + imgcurTime+".jpg"之后替换ImageCropFunction()【参考方案2】:

https://github.com/ArthurHub/Android-Image-Cropper 使用这个库。使用起来非常简单

【讨论】:

请访问该链接。那里给出的每个示例代码。

以上是关于如何裁剪图像并将其存储在 gridview 中?的主要内容,如果未能解决你的问题,请参考以下文章

裁剪图像并将其调整为特定尺寸

如何在存储 SD 卡之前裁剪捕获的图像? [复制]

图像裁剪以适合 GridView

在 C# 中正确裁剪图像并将其缩放到 1024 x 768 分辨率

使用 Imagemagick 裁剪图像的一部分并将其粘贴到另一个图像中不起作用

用 python 裁剪手机图像