Crop image to square - Android

KiKo

How can I cut rectangular image (600 x 300) from left and right to fit in square ImageView ? I don't want to resize image, I just want to crop it, to be 300 x 300.

[SOLUTION]

As @blackbelt said

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

is great for cropping images. So how can you automatically crop images with different sizes. I create this simple code for that:

// 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);
Blackbelt

You can use

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

from the documentation:

Returns an immutable bitmap from the specified subset of the source bitmap. The new bitmap may be the same object as source, or a copy may have been made. It is initialized with the same density as the original bitmap.

Here you can find the documentation

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related