将图像裁剪为正方形 - Android

22

如何将矩形图像(600 x 300)从左侧和右侧剪切以适合正方形 ImageView?我不想调整图像大小,我只想裁剪它,使其为 300 x 300。

[解决方法]

就像 @blackbelt 所说的那样

Bitmap cropImg = Bitmap.createBitmap(src, startX, startY, dstWidth, dstHeight);

非常适合裁剪图片。那么如何自动裁剪不同尺寸的图片呢?我创建了这个简单的代码:

// From drawable
Bitmap src= BitmapFactory.decodeResource(context.getResources(), R.drawable.image);

// From URL
Bitmap src = null;
try {
    String URL = "http://www.example.com/image.jpg";
    InputStream in = new java.net.URL(URL).openStream();
    src = BitmapFactory.decodeStream(in);
} catch (Exception e) {
    e.printStackTrace();
}

int width = src.getWidth();
int height = src.getHeight();
int crop = (width - height) / 2;
Bitmap cropImg = Bitmap.createBitmap(src, crop, 0, height, height);

ImageView.setImageBitmap(cropImg);
4个回答

29

对上面的答案进行一点扩展

由于在某些情况下,使用Bitmap.createBitmap()可能会出现异常或不符合预期的结果,例如以下情况:

java.lang.IllegalArgumentException: x + width must be <= bitmap.width()

这里有一个小函数来裁剪并处理一些常见情况。

编辑: 根据droidster的说法进行了更新。

public static Bitmap cropToSquare(Bitmap bitmap){
    int width  = bitmap.getWidth();
    int height = bitmap.getHeight();
    int newWidth = (height > width) ? width : height;
    int newHeight = (height > width)? height - ( height - width) : height;
    int cropW = (width - height) / 2;
    cropW = (cropW < 0)? 0: cropW;
    int cropH = (height - width) / 2;
    cropH = (cropH < 0)? 0: cropH;
    Bitmap cropImg = Bitmap.createBitmap(bitmap, cropW, cropH, newWidth, newHeight);

    return cropImg;
}

我使用了几张不同分辨率和大小的图片进行了测试,并且它按预期工作。

在其他情况下也可以使用,例如当您尝试制作“完美”的圆形图像并且需要传递一个方形位图时等等。


1
这正是我一直在寻找的,可以得到完美圆形图像而不是椭圆形。然而,如果图像的高度大于宽度,则不会在中心裁剪,因为createBitmap方法中y参数的值为0。以下是如何解决此问题:添加这两行代码:int cropH = (height - width) / 2; cropH = (cropH < 0)? 0: cropH; 将cropH用作y值。 Bitmap cropImg = Bitmap.createBitmap(bitmap, cropW, cropH, newWidth, newHeight); - Rahul Sainani
好的,我明白你的意思了。基本上需要对宽度和高度进行相同的计算。 - cass

7
设置固定的图像视图高度和宽度,并为图像视图设置两个属性。
android:adjustViewBounds="true" 
android:scaleType="centerCrop"

done


4
您可以使用

标签。

Bitmap dst = Bitmap.createBitmap(src, startX, startY, dstWidth, dstHeight);

来自文档:

从指定的源位图子集返回一个不可变位图。新位图可能是与源相同的对象,也可能已经复制了一份。它以与原始位图相同的密度初始化。

在这里您可以找到该文档


0

现在XML具有以下属性:

 custom:cropAspectRatioX="2"
    custom:cropAspectRatioY="1"

如果您想进行正方形裁剪,请将两个值都设置为1。现在它是矩形的。

添加CropActivity活动

       package agropost.post.agro.com.agropost.Activity;

    import android.content.Intent;
    import android.graphics.Bitmap;
    import android.graphics.BitmapFactory;
    import android.os.Bundle;
    import android.support.v7.app.AppCompatActivity;
    import android.util.DisplayMetrics;
    import android.widget.Button;

    import com.theartofdev.edmodo.cropper.CropImageView;

    import agropost.post.agro.com.agropost.R;
    import agropost.post.agro.com.agropost.Utility.Constants;
    import butterknife.BindView;
    import butterknife.ButterKnife;
    import butterknife.OnClick;

    public class CropActivity extends AppCompatActivity {


        public static boolean isCrop = false;
        @BindView(R.id.img_crop)
        CropImageView imgCrop;
        @BindView(R.id.btn_done)
        Button btnDone;
        @BindView(R.id.btn_cancel)
        Button btnCancel;




        @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_crop);
            ButterKnife.bind(this);


            DisplayMetrics displayMetrics = new DisplayMetrics();
            getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
            int width = displayMetrics.widthPixels;
            width = width - 80;
            imgCrop.getLayoutParams().height = width;
            imgCrop.getLayoutParams().width = width;

            imgCrop.setBackground(null);
            imgCrop.setScaleType(CropImageView.ScaleType.FIT_CENTER);



                imgCrop.setImageBitmap(Constants.mDashboardActivity.thumbnail_r);



        }

        @OnClick(R.id.btn_done)
        public void onViewClicked() {

            isCrop = true;
            Intent returnIntent = new Intent();



                Constants.mDashboardActivity.thumbnail_r = imgCrop.getCroppedImage();
                setResult(3, returnIntent);



            finish();
        }

        @OnClick(R.id.btn_cancel)
        public void onViewClickedCancel() {

            byte[] byteArray = getIntent().getByteArrayExtra("default");
            Bitmap bmp = BitmapFactory.decodeByteArray(byteArray, 0, byteArray.length);


            Constants.mDashboardActivity.thumbnail_r = bmp;
            isCrop = true;
            Intent returnIntent = new Intent();
            setResult(3, returnIntent);

            finish();
        }


       @Override
        public void onBackPressed() {
            //  super.onBackPressed();


        }


    }

活动的XML……

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout 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"
    android:background="@color/transparent"
    android:gravity="center"
    android:orientation="vertical"
    tools:context=".Activity.CropActivity">


    <com.theartofdev.edmodo.cropper.CropImageView xmlns:custom="http://schemas.android.com/apk/res-auto"
        android:id="@+id/img_crop"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:background="@drawable/drawer_bg"
        android:scaleType="centerInside"
        custom:cropAspectRatioX="2"
        custom:cropAspectRatioY="1"
        custom:cropFixAspectRatio="true"
        custom:cropShape="rectangle" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_done"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_marginLeft="@dimen/margin_40"
            android:layout_marginRight="@dimen/margin_20"
            android:layout_marginTop="@dimen/margin_20"
            android:layout_weight="1"
            android:background="@drawable/btn_bg_green_rounded"
            android:text="Done"
            android:textColor="@color/colorWhite"

            android:textSize="@dimen/fontsize_normal" />

        <Button
            android:id="@+id/btn_cancel"
            android:layout_width="match_parent"
            android:layout_height="60dp"
            android:layout_marginLeft="@dimen/margin_20"
            android:layout_marginRight="@dimen/margin_40"
            android:layout_marginTop="@dimen/margin_20"
            android:layout_weight="1"
            android:background="@drawable/btn_bg_green_rounded"
            android:text="Cancel"
            android:textColor="@color/colorWhite"
            android:textSize="@dimen/fontsize_normal"

            android:visibility="gone" />
    </LinearLayout>

</LinearLayout>

添加依赖

      implementation 'com.theartofdev.edmodo:android-image-cropper:2.4.+'

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接