Ive been looking around but couldn't find the solution to my problem. Im am trying to pass the bmp1 to the second activity, Profile. The code pasted does not work, anyone with possible suggestions would be great.
Here is my code for the first part
Bitmap bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions);
int heightRatio = (int)Math.ceil(bmpFactoryOptions.outHeight/(float)dh);
int widthRatio = (int)Math.ceil(bmpFactoryOptions.outWidth/(float)dw);
if (heightRatio > 1 && widthRatio > 1)
{
if (heightRatio > widthRatio) {
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
bmpFactoryOptions.inJustDecodeBounds = false;
bmp = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions);
Bitmap bmp1 = BitmapFactory.decodeStream(getContentResolver().openInputStream(imageFileUri), null, bmpFactoryOptions);
Bitmap alteredBitmap = Bitmap.createBitmap(bmp1.getWidth(),bmp1.getHeight(), bmp1.getConfig());
Canvas canvas = new Canvas(alteredBitmap);
Paint paint = new Paint();
Matrix matrix = new Matrix();
matrix.setValues(new float[] {
.5f, 0, 0,
0, .5f, 0,
0, 0, 1
});
canvas.drawBitmap(bmp, matrix, paint);
ImageView alteredImageView = (ImageView) this.findViewById(R.id.AlteredImageView);
alteredImageView.setImageBitmap(alteredBitmap);
chosenImageView.setImageBitmap(bmp1);
} catch (FileNotFoundException e) { Log.v("ERROR",e.toString());
}
}
Nex.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
//Uri imageFileUri = intent.getData();
Intent intent = new Intent(Choose.this, Profile.class);
// your bitmap
ByteArrayOutputStream bs = new ByteArrayOutputStream();
bmp1.compress(Bitmap.CompressFormat.PNG, 50, bs);
intent.putExtra("byteArray", bs.toByteArray());
intent.putExtra("location", textView1.getText().toString());
startActivity(intent);
}
}
);
}
}
public class Profile extends Activity {
ImageView picture;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.profile);
picture = (ImageView) findViewById(R.id.Picture);
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("bytearray");
use
intent.putExtra("BitmapImage", bmp1);
and
Bitmap bitmap = (Bitmap) intent.getParcelableExtra("BitmapImage");
No need to think this much..
take one static Bitmap in Choose Activity and use it in Profile Activity.
Hope this will help you to understand:
Choose.java
static Bitmap bit=null;
//then assign bitmap when it available
bit=bmp1 //this is your bitmap
//now at Profile.java use Choose.bit
if(Choose.bit!=null)
{
profimageview.setBitmap(Choose.bit);
}
There is a mistake in your code. you are using String "byteArray" as Key for putting byte array but retrieving in Profile Activity with different String Key "Image"
Related
I have an image of women. I find her eye points using FaceDetector. Now I want to add hair image over her face using those eyes points.
I am loading that image from gallery using below code
btnLoad.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent intent = new Intent();
intent.setType("image/*");
intent.setAction(Intent.ACTION_GET_CONTENT);
intent.addCategory(Intent.CATEGORY_OPENABLE);
startActivityForResult(intent, RQS_LOADIMAGE);
}
});
In onActivityResult, i am checking the face cordinates
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
try {
InputStream inputStream = getContentResolver().openInputStream(data.getData());
myBitmap = BitmapFactory.decodeStream(inputStream);
inputStream.close();
imgView.setImageBitmap(myBitmap);
if (myBitmap == null) {
Toast.makeText(MainActivity.this, "myBitmap == null", Toast.LENGTH_LONG).show();
} else {
detectFace();
}
} catch (IOException e) {
e.printStackTrace();
}
}
Face Detection method
private void detectFace() {
Paint myRectPaint = new Paint();
myRectPaint.setStrokeWidth(5);
myRectPaint.setColor(Color.RED);
myRectPaint.setStyle(Paint.Style.STROKE);
tempBitmap = Bitmap.createBitmap(myBitmap.getWidth(), myBitmap.getHeight(), Bitmap.Config.RGB_565);
Canvas tempCanvas = new Canvas(tempBitmap);
tempCanvas.drawBitmap(myBitmap, 0, 0, null);
FaceDetector faceDetector = new FaceDetector.Builder(this)
.setTrackingEnabled(true)
.setLandmarkType(FaceDetector.ALL_LANDMARKS)
.setMode(FaceDetector.ACCURATE_MODE)
.setClassificationType(FaceDetector.ALL_CLASSIFICATIONS)
.build();
Frame frame = new Frame.Builder().setBitmap(myBitmap).build();
SparseArray<Face> faces = faceDetector.detect(frame);
imgView.setImageDrawable(new BitmapDrawable(getResources(), drawOnFace(faces)));
}
Getting Eye coordinates using below code :-
private Bitmap drawOnFace(SparseArray<Face> faceArray) {
tempBitmap = Bitmap.createBitmap(myBitmap.getWidth(), myBitmap.getHeight(), Bitmap.Config.RGB_565);
Canvas canvas = new Canvas(tempBitmap);
canvas.drawBitmap(myBitmap, 0, 0, null);
for (int i = 0; i < faceArray.size(); i++) {
Face face = faceArray.get(i);
for (Landmark landmark : face.getLandmarks()) {
switch (landmark.getType()) {
case Landmark.LEFT_EYE:
drawPoint(canvas, landmark.getPosition());
break;
case Landmark.RIGHT_EYE:
drawPoint(canvas, landmark.getPosition());
break;
}
}
}
return tempBitmap;
}
Draw circle over eyes using below code :-
private void drawPoint(Canvas canvas, PointF point) {
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setStrokeWidth(8);
paint.setStyle(Paint.Style.STROKE);
float x = point.x;
float y = point.y;
canvas.drawCircle(x, y, 10, paint);
}
Now inside DrawPoint method, I have eye coordinates. I want to use those points to put hair image over face.
I really don't know what to do next. Appreciate help guys.
Thank you in advance
To place image over camera preview use this code
float left=0,top=0;
Bitmap bitmap= BitmapFactory.decodeResource(getResources(),R.drawable.mustache);
//if you are in non activity then use context.getResources()
canvas.drawBitmap(bitmap,left,top,paint);
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.
how can I convert a Picture into a Bitmap, what I tried in the code is not working. Any Ideas on how to do this? I wanted to get the image in the Picture object and put that image into the ImageView named imageOne.
showBitmap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Picture picture = wv.capturePicture();
Bitmap bm = Bitmap.createBitmap(picture.getWidth(),
picture.getHeight(),
Bitmap.Config.RGB_565);
Canvas c = new Canvas(bm);
picture.draw(c);
imageOne.setImageBitmap(bm);
}
});
Add this:
//Convert Picture to Bitmap
private static Bitmap pictureDrawable2Bitmap(Picture picture) {
PictureDrawable pd = new PictureDrawable(picture);
Bitmap bitmap = Bitmap.createBitmap(pd.getIntrinsicWidth(), pd.getIntrinsicHeight(), Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawPicture(pd.getPicture());
return bitmap;
}
Reference: Android - How to convert picture from webview.capturePicture() to byte[] and back to bitmap
Then modify your code as follows:
showBitmap.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Picture picture = wv.capturePicture();
Bitmap bm = pictureDrawable2Bitmap(picture);
imageOne.setImageBitmap(bm);
}
});
private static Bitmap pictureDrawable2Bitmap(Picture picture) {
final int width = picture.getwidth();
final int height = picture.getHeight();
Bitmap bitmap = Bitmap.createBitmap(width, height, Config.ARGB_8888);
Canvas canvas = new Canvas(bitmap);
canvas.drawPicture(picture, new Rect(0, 0, width, height));
return bitmap;
}
The first file allow the user to pick a photo from the gallery and sends it to an activity which will process it. The problem is that the image is too large for the phone's screen, so you only see the top corner of the image(as if it has been magnified).
Button useGallery = (Button)findViewById(R.id.loadfromgallery);
useGallery.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
photoPickerIntent.setType("image/*");
startActivityForResult(photoPickerIntent, SELECT_PHOTO);
}}) ;
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent imageReturnedIntent) {
super.onActivityResult(requestCode, resultCode, imageReturnedIntent);
switch(requestCode) {
case SELECT_PHOTO:
if(resultCode == RESULT_OK){
Uri selectedImage = imageReturnedIntent.getData();
InputStream imageStream = null;
try {
imageStream = getContentResolver().openInputStream(selectedImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Bitmap yourSelectedImage = BitmapFactory.decodeStream(imageStream);
Intent intent = new Intent(mContext, DisplayUndistortedBitmapFromGalleryActivity.class);
intent.setData(selectedImage);
startActivity(intent);
if(yourSelectedImage != null){
Log.e(TAG,"pic ok");
}else{
Log.e(TAG,"pic not ok");
}
}
}
. The 2nd file is the activity that recieves the image data from the intent and places it in a URI that a bitmap is the derived from.
public class DisplayUndistortedBitmapFromGalleryActivity extends Activity {
private static final String TAG = "*********DUBFGActivity";
private Context mContext = this;
Uri uri;
private Bitmap mbitmap = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
uri = getIntent().getData();
if(uri != null){
Log.e(TAG, "uri ok");
}else {
Log.e(TAG, "uri not ok");
}
try {
mbitmap = Media.getBitmap(getContentResolver(), uri);
//setMbitmap(bitmap);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
.
I have a 3rd file which is the customview for the activity. The line below retrieves the bitmap from it's activity and displays it. Is there a way of downsizing the bitmap so it fits on the screen? thanks.
Bitmap bm = ((DisplayUndistortedBitmapFromGalleryActivity)getContext()).getMbitmap();
Here is how i usually resize a bitmap and is the easiest way.
public class bitmaptest extends Activity {
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
LinearLayout linLayout = new LinearLayout(this);
// load the origial BitMap (500 x 500 px)
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.android);
int width = bitmapOrg.width();
int height = bitmapOrg.height();
int newWidth = 200;
int newHeight = 200;
// calculate the scale - in this case = 0.4f
float scaleWidth = ((float) newWidth) / width;
float scaleHeight = ((float) newHeight) / height;
// createa matrix for the manipulation
Matrix matrix = new Matrix();
// resize the bit map
matrix.postScale(scaleWidth, scaleHeight);
// rotate the Bitmap
// recreate the new Bitmap
Bitmap resizedBitmap = Bitmap.createBitmap(bitmapOrg, 0, 0,
width, height, matrix, true);
// make a Drawable from Bitmap to allow to set the BitMap
// to the ImageView, ImageButton or what ever
BitmapDrawable bmd = new BitmapDrawable
EDIT:
Here is another option.
int targetWidth = bitmapOrg.getWidth() - 15; //change this to control the size
int targetHeight = bitmapOrg.getHeight() - 15 ;
Matrix matrix = new Matrix();
matrix.postScale(1f, 1f);
Bitmap resizedBitmap = Bitmap.createBitmap(bmp, 0, 0, targetWidth, targetHeight, matrix, true);
my api is 2.2,so i used camera.setDisplayOrientation(90) to make the preview is Portrait,this work very well,but when i save the pic to sd,the pic is horizontal not Portrait.when i used :
#Override
protected Bitmap doInBackground(String... params) {
int w = bmp.getWidth();
int h = bmp.getHeight();
// Setting post rotate to 90
Matrix mtx = new Matrix();
mtx.postRotate(90);
// Rotating Bitmap
Bitmap rotatedBMP = Bitmap.createBitmap(bmp, 0, 0, w, h, mtx, true);
bmp.recycle();
return rotatedBMP;
}
#Override
protected void onPostExecute(Bitmap result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
dialog.dismiss();
ivNewPhoto.setImageBitmap(result);
resultPath = ConstValue.MY_ALBUM_DIR + "/" + System.currentTimeMillis() + ".jpg";
ImageFile.writePhotoJpg(result), resultPath);
previewView.setVisibility(View.VISIBLE);
}
bmp is the Snapshot pic but i have mistakes:
Activity com.android.SuperPictureSearch.photo.PhotoActivity has leaked window com.android.internal.policy.impl.PhoneWindow$DecorView#43abb200 that was originally added here
can you tell me how to save the pic is Portrait,thank you
public void onPictureTaken(byte[] data, Camera camera) {
Bitmap mutableBitmap = null;
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bm= BitmapFactory.decodeByteArray(data, 0, data.length, options);
mutableBitmap =Bitmap.createScaledBitmap( bm , h, w,true);
bm.recycle();
Matrix matri = new Matrix();
matri.postRotate(90);
Bitmap mBitmap = Bitmap.createBitmap(mutableBitmap, 0, 0, mutableBitmap.getWidth(), mutableBitmap.getHeight(), matri, true);
mutableBitmap.recycle();
because the pic is too big form camera,so i size it