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
Related
here is my code :
ImageView mImageView = (ImageView)findViewById(R.id.imageView1);
// Bitmap bmp =drawTextToBitmap(this,R.drawable.man,"Hello Android");
Bitmap bmp =drawTextArrayToBitmap(this,R.drawable.man,"Smile");
mImageView.setImageBitmap(bmp);
now here is my method :
public Bitmap drawTextArrayToBitmap(Context mContext, int resourceId,String mText) {
try {
Resources resources = mContext.getResources();
float scale = resources.getDisplayMetrics().density;
Bitmap bitmap = BitmapFactory.decodeResource(resources, resourceId);
android.graphics.Bitmap.Config bitmapConfig = bitmap.getConfig();
if(bitmapConfig == null) {
bitmapConfig = android.graphics.Bitmap.Config.ARGB_8888;
}
bitmap = bitmap.copy(bitmapConfig, true);
Canvas canvas = new Canvas(bitmap);
Paint paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setColor(Color.rgb(110,110, 110));
paint.setTextSize((int) (12 * scale));
paint.setShadowLayer(1f, 0f, 1f, Color.DKGRAY);
Rect bounds = new Rect();
paint.getTextBounds(mText, 0, mText.length(), bounds);
/* int x = (bitmap.getWidth() - bounds.width())/6;
int y = (bitmap.getHeight() + bounds.height())/5;*/
int x = 100, y = 100;
for(int i=0;i<20;i++)
{
canvas.drawText(mText, x * scale, y * scale, paint);
}
return bitmap;
} catch (Exception e) {
// TODO: handle exception
return null;
}
}
}
I am working on an android application like image filter I want to make an image like this after using a filter over an image
After searching on StackOverflow I got this solution only and this is not like as I want to implement: I got like this
canvas.drawText("This is", 100, 100, mTextPaint);
canvas.drawText("multi-line", 100, 150, mTextPaint);
canvas.drawText("text", 100, 200, mTextPaint);
I do not want to do like this : please help me I would approciate your answers and suggestion
I want to crop face from image . I have an imageview .
iv1 = (ImageView) MainActivity.this.findViewById(R.id.img1);
When I click this imageview it pick one image from Gallery . The code is as below :
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 have added the code for cropping face from choosen image . The code is as below :
#Override
protected void onActivityResult(int requestCode, int resultCode,
Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch (requestCode)
{
case SELECT_PHOTO:
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();
bmpimg1 = yourSelectedImage;
viewHeight = iv1.getMeasuredHeight();
viewWidth = iv1.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;
android.media.FaceDetector.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.setBackgroundDrawable(new BitmapDrawable(
getCroppedBitmap(bd.getBitmap())));
} catch (Exception e) {
System.out.println("Error1 : " + e.getMessage()
+ e.toString());
}
iv1.invalidate();
}
else if (resultCode == RESULT_OK && imgNo == 2)
{
Bitmap photo = (Bitmap) imageReturnedIntent.getExtras().get("data");
iv2.setImageBitmap(photo);
// path2 = imageReturnedIntent.getData().getPath();
bmpimg2 = photo;
iv2.invalidate();
}
}
}
But the image is not cropping . How can I crop face from image ? Any advice is of great help .
To crop faces automatically, you have to instantiate an object of FaceCropper class in that way:
AndroidFaceCropper library download from github
https://github.com/lafosca/AndroidFaceCropper
You can use this library for croping faces from images.
This will produce result like this.
You can also select face type like.
Final result.
Im taking a screenshot of my app and try to post it on facebook using the facebook SDK. But as the ShareDialog appears with the Image, it´s upside down.. So I need to re-rotate it.
This is how I create the image:
private void saveScreenshot() {
try{
FileHandle fh;
do{
fh = new FileHandle(Gdx.files.getLocalStoragePath() + "stoneIMG" + counter++ + ".png");
}while(fh.exists());
Pixmap pixmap = getScreenshot(0, 0, Gdx.graphics.getWidth(), Gdx.graphics.getHeight(), false);
PixmapIO.writePNG(fh, pixmap);
pixmap.dispose();
System.out.println(fh.toString());
}catch(Exception e) {
}
}
And here I fetch it:
private Pixmap getScreenshot(int x, int y, int w, int h, boolean yDown){
final Pixmap pixmap = ScreenUtils.getFrameBufferPixmap(x, y, w, h);
if(yDown) {
ByteBuffer pixels = pixmap.getPixels();
int numBytes = w * h * 4;
byte[] lines = new byte[numBytes];
int numBytesPerLine = w * 4;
for (int i = 0; i < h; i++) {
pixels.position((h - i - 1) * numBytesPerLine);
pixels.get(lines, i * numBytesPerLine, numBytesPerLine);
}
pixels.clear();
pixels.put(lines);
}
return pixmap;
}
Then I try to share the photo:
public void sharePhoto() {
String filePath = Gdx.files.getLocalStoragePath() + "stoneIMG" + counter + ".png";
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
If you want to rotate a bitmap by 180 degrees you can use this code:
Bitmap bitmap = BitmapFactory.decodeFile(filePath, options);
Matrix matrix = new Matrix();
matrix.postRotate(180);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap , 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, true);
In one of my application i need to do masking( overlapping 1 image to another image)
In my app i have to load 1 image(Bitmap) to imageview then have to apply some fram to that image i have used another imageview for that... this is totally working
My problem is that..
When i am going to save the bitmap...
using this pice of code
public static Bitmap overlay(Bitmap bmp1, Bitmap bmp2) {
Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bmp1, new Matrix(), null);
canvas.drawBitmap(bmp2, 0, 0, null);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmOverlay.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator
+ "test.jpg");
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
return bmOverlay;
}
i am getting
But i need it like
The best I found so far is this one:
public Bitmap overlay(Bitmap bmp1, Bitmap bmp2) {
Bitmap bmOverlay = Bitmap.createBitmap(bmp2.getWidth(), bmp2.getHeight(), bmp1.getConfig());
float left =(bmp2.getWidth() - (bmp1.getWidth()*((float)bmp2.getHeight()/(float)bmp1.getHeight())))/(float)2.0;
float bmp1newW = bmp1.getWidth()*((float)bmp2.getHeight()/(float)bmp1.getHeight());
Bitmap bmp1new = getResizedBitmap(bmp1, bmp2.getHeight(), (int)bmp1newW);
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bmp1new, left ,0 , null);
canvas.drawBitmap(bmp2, new Matrix(), null);
return bmOverlay;
}
public Bitmap getResizedBitmap(Bitmap bm, int newHeight, int newWidth) {
int width = bm.getWidth();
int height = bm.getHeight();
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
Matrix matrix = new Matrix();
matrix.postScale(scaleWidth, scaleHeight);
Bitmap resizedBitmap = Bitmap.createBitmap(bm, 0, 0, width, height, matrix, false);
return resizedBitmap;
}
public static Bitmap overlay(Bitmap bmp1, Bitmap bmp2) {
Bitmap bmOverlay = Bitmap.createBitmap(bmp1.getWidth(), bmp1.getHeight(), bmp1.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(bmp1, new Matrix(), null);
// determine the width of the canvas
int canvasWidth = canvas.getWidth();
int canvasHeight = canvas.getHeight();
//resize your bmp2
Bitmap resized = Bitmap.createScaledBitmap(bmp2, canvasWidth, canvasHeight, true);
// determine the centre of the canvas
int centreX = (canvasWidth - resized .getWidth()) /2;
int centreY = (canvasHeight - resized .getHeight()) /2
// This code can be used to alter the opacity of the image being overlayed.
//http://stackoverflow.com/a/12235235/1635441
//http://stackoverflow.com/a/5119093/1635441
//Paint p = new Paint();
//p.setXfermode(new PorterDuffXfermode(Mode.DST_ATOP)); //http://stackoverflow.com/a/17553502/1635441
//p.setAlpha(180);
//p.setARGB(a, r, g, b);
//canvas.drawBitmap(resized, centreX, centreY, p);
//canvas.drawBitmap(bmp2, 0, 0, null);
canvas.drawBitmap(resized, centreX, centreY, null);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmOverlay.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator
+ "test.jpg");
try {
f.createNewFile();
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
} catch (IOException e) {
e.printStackTrace();
}
return bmOverlay;
}
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.