Crop Image with face detection in android - android

I needed a demo where any image can be cropped with the face detection function.
FIXED
But after few surfing hours I didn't come to a single demo, so I prepared a single demo with conjunction of few demos that I found online.
I have prepared a demo to crop the image.
My demo crops the image rectangle, and circular as well.
Also it detects the face and crops the image according to the face detection.
I am using the following image to crop it.
And the screenshot of the crop result is :
The xml for the example is :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center"
android:orientation="vertical"
tools:context=".MainActivity" >
<View
android:id="#+id/part1"
android:layout_width="fill_parent"
android:layout_height="100dp" >
</View>
<View
android:id="#+id/part2"
android:layout_width="100dp"
android:layout_height="100dp"
android:layout_marginTop="30dp" >
</View>
</LinearLayout>
The java code for the Activity :
public class MainActivity extends Activity {
public View part1, part2;
int viewHeight, viewWidth;
private FaceDetector myFaceDetect;
private FaceDetector.Face[] myFace;
float myEyesDistance;
#SuppressWarnings("deprecation")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
part1 = findViewById(R.id.part1);
part2 = findViewById(R.id.part2);
part1.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
viewHeight = part1.getMeasuredHeight();
viewWidth = part1.getMeasuredWidth();
try {
Paint paint = new Paint();
paint.setFilterBitmap(true);
Bitmap bitmapOrg = BitmapFactory.decodeResource(
getResources(),
R.drawable.sachin_tendulkar_10102013);
int targetWidth = bitmapOrg.getWidth();
int targetHeight = bitmapOrg.getHeight();
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,
targetHeight, Bitmap.Config.ARGB_8888);
RectF rectf = new RectF(0, 0, viewWidth, viewHeight);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addRect(rectf, Path.Direction.CW);
canvas.clipPath(path);
canvas.drawBitmap(
bitmapOrg,
new Rect(0, 0, bitmapOrg.getWidth(), bitmapOrg
.getHeight()), new Rect(0, 0, targetWidth,
targetHeight), paint);
Matrix matrix = new Matrix();
matrix.postScale(1f, 1f);
BitmapFactory.Options bitmapFatoryOptions = new BitmapFactory.Options();
bitmapFatoryOptions.inPreferredConfig = Bitmap.Config.RGB_565;
bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.sachin_tendulkar_10102013,
bitmapFatoryOptions);
myFace = new FaceDetector.Face[5];
myFaceDetect = new FaceDetector(targetWidth, targetHeight,
5);
int numberOfFaceDetected = myFaceDetect.findFaces(
bitmapOrg, myFace);
Bitmap resizedBitmap = null;
if (numberOfFaceDetected > 0) {
PointF myMidPoint = null;
Face face = myFace[0];
myMidPoint = new PointF();
face.getMidPoint(myMidPoint);
myEyesDistance = face.eyesDistance();
if (myMidPoint.x + viewWidth > targetWidth) {
while (myMidPoint.x + viewWidth > targetWidth) {
myMidPoint.x--;
}
}
if (myMidPoint.y + viewHeight > targetHeight) {
while (myMidPoint.y + viewHeight > targetHeight) {
myMidPoint.y--;
}
}
resizedBitmap = Bitmap.createBitmap(bitmapOrg,
(int) (myMidPoint.x - myEyesDistance),
(int) (myMidPoint.y - myEyesDistance),
viewWidth, viewHeight, matrix, true);
} else {
resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
viewWidth, viewHeight, matrix, true);
}
/* convert Bitmap to resource */
// Bitmap resizedBitmap = Bitmap.createBitmap(targetBitmap,
// 0,
// 0, viewWidth, viewHeight, matrix, true);
BitmapDrawable bd = new BitmapDrawable(resizedBitmap);
part1.setBackgroundDrawable(bd);
} catch (Exception e) {
System.out.println("Error1 : " + e.getMessage()
+ e.toString());
}
}
});
part2.post(new Runnable() {
#Override
public void run() {
// TODO Auto-generated method stub
viewHeight = part2.getMeasuredHeight();
viewWidth = part2.getMeasuredWidth();
try {
Paint paint = new Paint();
paint.setFilterBitmap(true);
Bitmap bitmapOrg = BitmapFactory.decodeResource(
getResources(),
R.drawable.sachin_tendulkar_10102013);
int targetWidth = bitmapOrg.getWidth();
int targetHeight = bitmapOrg.getHeight();
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,
targetHeight, Bitmap.Config.ARGB_8888);
RectF rectf = new RectF(0, 0, viewWidth, viewHeight);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addRect(rectf, Path.Direction.CW);
canvas.clipPath(path);
canvas.drawBitmap(
bitmapOrg,
new Rect(0, 0, bitmapOrg.getWidth(), bitmapOrg
.getHeight()), new Rect(0, 0, targetWidth,
targetHeight), paint);
Matrix matrix = new Matrix();
matrix.postScale(1f, 1f);
BitmapFactory.Options bitmapFatoryOptions = new BitmapFactory.Options();
bitmapFatoryOptions.inPreferredConfig = Bitmap.Config.RGB_565;
bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.sachin_tendulkar_10102013,
bitmapFatoryOptions);
myFace = new FaceDetector.Face[5];
myFaceDetect = new FaceDetector(targetWidth, targetHeight,
5);
int numberOfFaceDetected = myFaceDetect.findFaces(
bitmapOrg, myFace);
Bitmap resizedBitmap = null;
if (numberOfFaceDetected > 0) {
PointF myMidPoint = null;
Face face = myFace[0];
myMidPoint = new PointF();
face.getMidPoint(myMidPoint);
myEyesDistance = face.eyesDistance() + 20;
if (myMidPoint.x + viewWidth > targetWidth) {
while (myMidPoint.x + viewWidth > targetWidth) {
myMidPoint.x--;
}
}
if (myMidPoint.y + viewHeight > targetHeight) {
while (myMidPoint.y + viewHeight > targetHeight) {
myMidPoint.y--;
}
}
resizedBitmap = Bitmap.createBitmap(bitmapOrg,
(int) (myMidPoint.x - myEyesDistance),
(int) (myMidPoint.y - myEyesDistance),
viewWidth, viewHeight, matrix, true);
} else {
resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
viewWidth, viewHeight, matrix, true);
}
/* convert Bitmap to resource */
// Bitmap resizedBitmap = Bitmap.createBitmap(targetBitmap,
// 0,
// 0, viewWidth, viewHeight, matrix, true);
BitmapDrawable bd = new BitmapDrawable(resizedBitmap);
part2.setBackgroundDrawable(new BitmapDrawable(
getCroppedBitmap(bd.getBitmap())));
} catch (Exception e) {
System.out.println("Error1 : " + e.getMessage()
+ e.toString());
}
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
public Bitmap getCroppedBitmap(Bitmap bitmap) {
// Bitmap output = Bitmap.createBitmap(bitmap.getWidth(),
// bitmap.getHeight(), Config.ARGB_8888);
// Canvas canvas = new Canvas(output);
//
// final int color = 0xff424242;
// final Paint paint = new Paint();
// final Rect rect = new Rect(0, 0, bitmap.getWidth(),
// bitmap.getHeight());
//
// paint.setAntiAlias(true);
// canvas.drawARGB(0, 0, 0, 0);
// paint.setColor(color);
// // canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
// canvas.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2,
// bitmap.getWidth() / 2, paint);
// paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
// canvas.drawBitmap(bitmap, rect, rect, paint);
// // Bitmap _bmp = Bitmap.createScaledBitmap(output, 60, 60, false);
// // return _bmp;
// return output;
int targetWidth = bitmap.getWidth();
int targetHeight = bitmap.getHeight();
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight,
Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addCircle(((float) targetWidth - 1) / 2,
((float) targetHeight - 1) / 2,
(Math.min(((float) targetWidth), ((float) targetHeight)) / 2),
Path.Direction.CCW);
canvas.clipPath(path);
Bitmap sourceBitmap = bitmap;
canvas.drawBitmap(sourceBitmap, new Rect(0, 0, sourceBitmap.getWidth(),
sourceBitmap.getHeight()), new Rect(0, 0, targetWidth,
targetHeight), null);
return targetBitmap;
}
}

The demo works for any image put in the drawable folder,
But if you want to crop any dynamic image, for example any image which is downloaded or chosen from gallery, make few changes in the code :
See the line :
Bitmap bitmapOrg = BitmapFactory.decodeResource(
getResources(),
R.drawable.sachin_tendulkar_10102013);
Here I am taking the image from the drawable folder, now for any downloaded image, you just need to save that image in the bitmapOrg variable, so just change the above line twice, one for part1 for rectangle and part2 for ciculart with your downloaded image saving to bitmapOrg as bitmap, and use the demo, it will crop your image in rectangle and circular way.

Related

How to get particular cropping image using canvas circular image?

I am create a custom ImageView with Pinch IN-OUT zoom and circular crop image.The Pinch in-out is wroking fine but when i trying to cropping image, can't get the particulr circle image. I'm using Pinch in-out working based on onTuchListener and Circular Cropping based on canvas class.
I have used below mentioned code for Pinch in-out and Circle Crop image:
#Override
protected void onDraw(Canvas canvas) {
onDrawReady = true;
imageRenderedAtLeastOnce = true;
if (delayedZoomVariables != null) {
setZoom(delayedZoomVariables.scale, delayedZoomVariables.focusX, delayedZoomVariables.focusY, delayedZoomVariables.scaleType);
delayedZoomVariables = null;
}
super.onDraw(canvas);
if (bitmap == null) {
circleWindowFrame(); //Creating circle view
}
canvas.drawBitmap(bitmap, 0, 0, null);
}
protected void circleWindowFrame() {
bitmap = Bitmap.createBitmap(getWidth(), getHeight(), Bitmap.Config.ARGB_8888);
Canvas osCanvas = new Canvas(bitmap);
RectF outerRectangle = new RectF(0, 0, bitmap.getWidth(), bitmap.getHeight());
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(getResources().getColor(R.color.overlay));
paint.setAlpha(99);
osCanvas.drawRect(outerRectangle, paint);
paint.setColor(Color.TRANSPARENT);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_OUT));
float centerX = getWidth() / 2;
float centerY = getHeight() / 2;
DisplayMetrics metrics = context.getResources().getDisplayMetrics();
int width = metrics.widthPixels;
float radius = width / 2;
osCanvas.drawCircle(centerX, centerY, radius, paint);
}
This code for Cropping:
public static Bitmap getCrop() {
Bitmap circleBitmap;
circleBitmap = Bitmap.createBitmap(bitmap.getWidth(), bitmap.getHeight(), Bitmap.Config.ARGB_8888);
BitmapShader shader = new BitmapShader(bitmap, Shader.TileMode.CLAMP, Shader.TileMode.CLAMP);
Paint paint = new Paint();
paint.setShader(shader);
paint.setAntiAlias(true);
Canvas c = new Canvas(circleBitmap);
c.drawCircle(bitmap.getWidth() / 2, bitmap.getHeight() / 2, bitmap.getWidth() / 2, paint);
return bitmap;
}
Thanks for Advance...
try this
public static Bitmap toOvalBitmap(#NonNull Bitmap bitmap) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Bitmap output = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(output);
int color = 0xff424242;
Paint paint = new Paint();
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
RectF rect = new RectF(0, 0, width, height);
canvas.drawOval(rect, paint);
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(bitmap, 0, 0, paint);
bitmap.recycle();
return output;
}

how to crop face from image in android

I want to crop face from image in android . After searching a lot in internet , I have come to know about this tutorial . I have an imageview .
iv1 = (ImageView) MainActivity.this.findViewById(R.id.img1);
When I tap this imageview I pick an image from Gallery . The code is as follows :
iv1.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
imgNo = 1;
}
});
In onActivityResult method , I am trying to crop face image according to the following code :
if (resultCode == RESULT_OK && imgNo == 1 )
{
selectedImage = imageReturnedIntent.getData();
try {
imageStream = getContentResolver().openInputStream(
selectedImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
yourSelectedImage = BitmapFactory.decodeStream(imageStream);
// iv1.setImageBitmap(yourSelectedImage);
path1 = selectedImage.getPath();
viewHeight = part2.getMeasuredHeight();
viewWidth = part2.getMeasuredWidth();
try {
Paint paint = new Paint();
paint.setFilterBitmap(true);
Bitmap bitmapOrg = yourSelectedImage;
int targetWidth = bitmapOrg.getWidth();
int targetHeight = bitmapOrg.getHeight();
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth,
targetHeight, Bitmap.Config.ARGB_8888);
RectF rectf = new RectF(0, 0, viewWidth, viewHeight);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
path.addRect(rectf, Path.Direction.CW);
canvas.clipPath(path);
canvas.drawBitmap(
bitmapOrg,
new Rect(0, 0, bitmapOrg.getWidth(), bitmapOrg
.getHeight()), new Rect(0, 0, targetWidth,
targetHeight), paint);
Matrix matrix = new Matrix();
matrix.postScale(1f, 1f);
BitmapFactory.Options bitmapFatoryOptions = new BitmapFactory.Options();
bitmapFatoryOptions.inPreferredConfig = Bitmap.Config.RGB_565;
bitmapOrg = yourSelectedImage;
myFace = new FaceDetector.Face[5];
myFaceDetect = new FaceDetector(targetWidth, targetHeight,
5);
int numberOfFaceDetected = myFaceDetect.findFaces(
bitmapOrg, myFace);
Bitmap resizedBitmap = null;
if (numberOfFaceDetected > 0) {
PointF myMidPoint = null;
Face face = myFace[0];
myMidPoint = new PointF();
face.getMidPoint(myMidPoint);
myEyesDistance = face.eyesDistance() + 20;
if (myMidPoint.x + viewWidth > targetWidth) {
while (myMidPoint.x + viewWidth > targetWidth) {
myMidPoint.x--;
}
}
if (myMidPoint.y + viewHeight > targetHeight) {
while (myMidPoint.y + viewHeight > targetHeight) {
myMidPoint.y--;
}
}
resizedBitmap = Bitmap.createBitmap(bitmapOrg,
(int) (myMidPoint.x - myEyesDistance),
(int) (myMidPoint.y - myEyesDistance),
viewWidth, viewHeight, matrix, true);
} else {
resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
viewWidth, viewHeight, matrix, true);
}
/* convert Bitmap to resource */
// Bitmap resizedBitmap = Bitmap.createBitmap(targetBitmap,
// 0,
// 0, viewWidth, viewHeight, matrix, true);
BitmapDrawable bd = new BitmapDrawable(resizedBitmap);
iv1.setImageBitmap(getCroppedBitmap(bd.getBitmap()));
} catch (Exception e) {
System.out.println("Error1 : " + e.getMessage()
+ e.toString());
}
iv1.invalidate();
}
But this code is not able to crop face from image picked from Gallery . How can I crop face from image ? Any advice is of great help .
You can try Facedetector built in class
FaceDetector.Face[] face=new FaceDetector.Face[20];
FaceDetector fd=new FaceDetector(200,200,2);
ImageView v=(ImageView)findViewById(R.id.imageView);
BitmapDrawable draw=(BitmapDrawable)v.getDrawable();
fd.findFaces(draw.getBitmap(), face);
//Now face will hold array face image

Optimize memory usage while cropping bitmap in rounded shape on Canvas

I am using a method which returns a rounded Bitmap with Fill: Transparent Color in outer spaces of canvas. I am using that method in a custom adaptor to display images in rounded shape in a list but for some reason fill adapter is throwing "OutOfMemoryError" Exception.
public static Bitmap getRoundedShape(Bitmap scaleBitmapImage, int width){
try {
int targetWidth = width;
int targetHeight = width;
Bitmap targetBitmap = Bitmap.createBitmap(targetWidth, targetHeight, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(targetBitmap);
Path path = new Path();
float x = ((float) targetWidth - 1) / 2;
float y = ((float) targetHeight - 1) / 2;
float radius = (Math.min(((float) targetWidth), ((float)targetHeight)) / 2);
path.addCircle(x, y, radius, Path.Direction.CCW);
canvas.clipPath(path);
Bitmap sourceBitmap = scaleBitmapImage;
Rect sourceRect = new Rect(0, 0, sourceBitmap.getWidth(), sourceBitmap.getHeight());
Rect destRect = new Rect(0, 0, targetWidth, targetHeight);
canvas.drawBitmap(sourceBitmap, sourceRect, destRect, null);
return targetBitmap;
} catch (Exception ex) {
return scaleBitmapImage;
}
}
Try setting variables to null. This helps GC free some memory.

Android Canvas How to scale Bitmap but keep original bound?

I want to scale a Bitmap using Canvas
I need to keep the Bitmap original width and height
and the scaled one aligns center-middle in bound
here is what I have tried:
public Bitmap scale(Bitmap src) {
int width = src.getWidth();
int height = src.getHeight();
float scaledWidth = width * .5f;
float scaledHeight = height * .5f;
Bitmap transBitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas canvas = new Canvas(transBitmap);
Paint paint = new Paint();
float dx = (width - scaledWidth);
float dy = (height - scaledHeight);
canvas.drawBitmap(src, null, new RectF(dx, dy, scaledWidth, scaledHeight), paint);
Matrix m = new Matrix();
m.setRectToRect(new RectF(0, 0, src.getWidth(), src.getHeight()), new RectF(0, 0, scaledWidth, scaledHeight), Matrix.ScaleToFit.CENTER);
Bitmap output = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), m, true);
//return transBitmap;
return output;
}
I used this method in custom ImageView onTouch:
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
setImageBitmap(scaledBmp);
break;
case MotionEvent.ACTION_UP:
setImageDrawable(originalDrawable);
break;
}
UPDATE
MyImageView.java
public class MyImageView extends ImageView {
private Drawable mDrawable;
private Drawable mScaled;
public MyImageView(Context context, Drawable drawable) {
super(context);
setImageDrawable(drawable);
Bitmap src = ((BitmapDrawable) drawable).getBitmap();
mDrawable = drawable;
mScaled = new BitmapDrawable(getResources(), makeScaled(src));
}
public Bitmap makeScaled(Bitmap src) {
int width = src.getWidth();
int height = src.getHeight();
float scaledWidth = width * .95f;
float scaledHeight = height * .95f;
Matrix m = new Matrix();
m.setRectToRect(new RectF(0, 0, src.getWidth(), src.getHeight()), new RectF(0, 0, scaledWidth, scaledHeight), Matrix.ScaleToFit.CENTER);
Bitmap output = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), m, true);
Canvas xfas = new Canvas(output);
Paint paint = new Paint();
paint.setAntiAlias(true);
paint.setFilterBitmap(true);
paint.setDither(true);
xfas.drawBitmap(output, 0, 0, paint);
return output;
}
#Override public boolean dispatchTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
setImageDrawable(mScaled);
break;
case MotionEvent.ACTION_UP:
setImageDrawable(mDrawable);
break;
}
return super.dispatchTouchEvent(event);
}
}
If I have not misunderstood, one solution is to use a Matrix and its setRectToRect to translate the original values to the desired one. From the documentation
Set the matrix to the scale and translate values that map the source
rectangle to the destination rectangle, returning true if the the
result can be represented.
Matrix m = new Matrix();
m.setRectToRect(new RectF(0, 0, src.getWidth(), src.getHeight()), new RectF(0, 0, scaledWidth, scaledHeigth), Matrix.ScaleToFit.CENTER);
Bitmap output = Bitmap.createBitmap(src, 0, 0, src.getWidth(), src.getHeight(), m, true);
and then simply draw the scaled bitmap on your canvas
Solved
public static Bitmap scaleBitmap(Bitmap src, float factor) {
int width = src.getWidth();
int height = src.getHeight();
int scaledWidth = (int) (width * factor);
int scaledHeight = (int) (height * factor);
Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Bitmap scaled = Bitmap.createScaledBitmap(src, scaledWidth, scaledHeight, false);
Canvas canvas = new Canvas(bmp);
Paint paint = new Paint();
int distX = (width - scaledWidth) / 2;
int distY = (height - scaledHeight) / 2;
canvas.drawBitmap(scaled, distX, distY, paint);
return bmp;
}

Add border to getRoundedCornerBitmap android

In getRoundedCornerBitmap(Context context, Bitmap input, int pixels , int w , int h , boolean squareTL, boolean squareTR, boolean squareBL, boolean squareBR ) method below i attempted to display rounded image but when i try to add a border around the circle nothing is displayed. How can i add border to this rounded method.
public static Bitmap getRoundedCornerBitmap(Context context, Bitmap input, int pixels , int w , int h , boolean squareTL, boolean squareTR, boolean squareBL, boolean squareBR ) {
Bitmap output = Bitmap.createBitmap(w, h, Config.ARGB_8888);
Canvas canvas = new Canvas(output);
final float densityMultiplier = context.getResources().getDisplayMetrics().density;
final int color = 0xff424242;
final Paint paint = new Paint();
final Rect rect = new Rect(0, 0, w, h);
final RectF rectF = new RectF(rect);
//make sure that our rounded corner is scaled appropriately
final float roundPx = pixels*densityMultiplier;
paint.setAntiAlias(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawRoundRect(rectF, roundPx, roundPx, paint);
//draw rectangles over the corners we want to be square
if (squareTL ){
canvas.drawRect(0, 0, w/2, h/2, paint);
}
if (squareTR ){
canvas.drawRect(w/2, 0, w, h/2, paint);
}
if (squareBL ){
canvas.drawRect(0, h/2, w/2, h, paint);
}
if (squareBR ){
canvas.drawRect(w/2, h/2, w, h, paint);
}
paint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.SRC_IN));
canvas.drawBitmap(input, 0,0, paint);
return output;
}
Update now the circle is cut from left and bottom. How can i get a full rounded image
Try below code :-
int w = bitmap.getWidth();
int h = bitmap.getHeight();
int radius = Math.min(h / 2, w / 2);
Bitmap output = Bitmap.createBitmap(w + 8, h + 8, Config.ARGB_8888);
Paint p = new Paint();
p.setAntiAlias(true);
Canvas c = new Canvas(output);
c.drawARGB(0, 0, 0, 0);
p.setStyle(Style.FILL);
c.drawCircle((w / 2) + 4, (h / 2) + 4, radius, p);
p.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
c.drawBitmap(bitmap, 4, 4, p);
p.setXfermode(null);
p.setStyle(Style.STROKE);
p.setColor(Color.WHITE);
p.setStrokeWidth(3);
c.drawCircle((w / 2) + 4, (h / 2) + 4, radius, p);
return output;
see below link for more info:-
How to add a shadow and a border on circular imageView android?
Adding a round frame circle on rounded bitmap
or use below code :-
imageViewUser.setImageBitmap(new GraphicsUtil().getCircleBitmap(GraphicsUtil.decodeSampledBitmapFromResource(filePath,120, 120))); // filepath is your image path
GraphicsUtil.java
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.RectF;
public class GraphicsUtil
{
/*
* Draw image in circular shape Note: change the pixel size if you want
* image small or large
*/
public Bitmap getCircleBitmap(Bitmap bitmap)
{
Bitmap output;
Canvas canvas = null;
final int color = 0xffff0000;
final Paint paint = new Paint();
Rect rect = null;
if (bitmap.getHeight() > 501)
{
output = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
canvas = new Canvas(output);
rect = new Rect(0, 0, 500, 500);
}
else
{
//System.out.println("output else =======");
bitmap = Bitmap.createScaledBitmap(bitmap, 500, 500, false);
output = Bitmap.createBitmap(500, 500, Bitmap.Config.ARGB_8888);
canvas = new Canvas(output);
rect = new Rect(0, 0, 500, 500);
}
final RectF rectF = new RectF(rect);
paint.setAntiAlias(true);
paint.setDither(true);
paint.setFilterBitmap(true);
canvas.drawARGB(0, 0, 0, 0);
paint.setColor(color);
canvas.drawOval(rectF, paint);
paint.setColor(Color.BLUE);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth((float) 1);
paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
canvas.drawBitmap(bitmap, rect, rect, paint);
return output;
}
public static int calculateInSampleSize(BitmapFactory.Options options, int reqWidth, int reqHeight)
{
// Raw height and width of image
final int height = options.outHeight;
final int width = options.outWidth;
int inSampleSize = 1;
if (height > reqHeight || width > reqWidth)
{
// Calculate ratios of height and width to requested height and
// width
final int heightRatio = Math.round((float) height / (float) reqHeight);
final int widthRatio = Math.round((float) width / (float) reqWidth);
// Choose the smallest ratio as inSampleSize value, this will
// guarantee
// a final image with both dimensions larger than or equal to the
// requested height and width.
inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
}
return inSampleSize;
}
public static Bitmap decodeSampledBitmapFromResource(String path, int reqWidth, int reqHeight)
{
// First decode with inJustDecodeBounds=true to check dimensions
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeFile(path, options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, reqWidth, reqHeight);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
return BitmapFactory.decodeFile(path, options);
}
}

Categories

Resources