【问题标题】:Crop image to square - Android将图像裁剪为正方形 - Android
【发布时间】:2014-10-08 18:14:24
【问题描述】:

如何从左右剪切矩形图像 (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);

【问题讨论】:

    标签: android android-imageview resize-crop


    【解决方案1】:

    稍微扩展一下上面的答案

    因为在某些情况下,您可能会得到异常或不是预期结果,只需通过使用 Bitmap.createBitmap(),就像下面这样:

    java.lang.IllegalArgumentException: x + width 必须是

    Heres 是一个小函数,用于裁剪和处理一些常见情况。

    编辑:根据 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;
    }
    

    我对一些不同分辨率和大小的图像进行了几次测试,结果按预期工作。

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

    【讨论】:

    • 这正是我一直在寻找的,以获得完美的圆形图像而不是椭圆形。但是,如果图像的高度大于宽度,则不会在中心进行裁剪,因为 createBitmap 方法中 y 参数的值为 0。解决方法如下: 添加这两行:int cropH = (height - width) / 2; cropH = (cropH &lt; 0)? 0: cropH; 使用cropH 作为y 值。 Bitmap cropImg = Bitmap.createBitmap(bitmap, cropW, cropH, newWidth, newHeight);
    • 很好,我明白你的意思了......基本上对宽度和高度进行相同的计算。
    【解决方案2】:

    设置固定的图像视图高度、宽度,并为图像视图设置两个属性

    android:adjustViewBounds="true" 
    android:scaleType="centerCrop"
    

    完成

    【讨论】:

      【解决方案3】:

      你可以使用

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

      来自文档:

      从源的指定子集中返回不可变位图 位图。新的位图可能与源是同一个对象,也可能是一个副本 已经做出来了。它被初始化为与 原始位图。

      Here你可以找到文档

      【讨论】:

        【解决方案4】:

        现在 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.+'
        

        【讨论】:

          猜你喜欢
          • 2023-03-21
          • 2012-04-23
          • 1970-01-01
          • 2020-02-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-12-30
          • 1970-01-01
          相关资源
          最近更新 更多