I have this multiple image in a canvas, how do I get the anchors of each image in the canvas and be able to drag, resize and move it on the canvas. Just like in the other image editor Android applications. Please help me. Thank you
here's the code:
public class MainActivity extends Activity implements OnClickListener {
static final int PICKED_ONE = 0;
static final int PICKED_TWO = 1;
boolean onePicked = false;
boolean twoPicked = false;
Button choosePicture1, choosePicture2;
ImageView compositeImageView;
Bitmap bmp1, bmp2;
Bitmap returnBmp;
Bitmap drawingBitmap;
Canvas canvas;
Paint paint;
protected static final String TAG = MainActivity.class.getName();
Bitmap mBackImage, mTopImage, mBackground, mInnerImage, mNewSaving;
Canvas mComboImage;
FileOutputStream mFileOutputStream;
BitmapDrawable mBitmapDrawable;
private String mCurrent = null;
private static String mTempDir;
Button save;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
save = (Button)findViewById(R.id.save);
mTempDir = Environment.getExternalStorageDirectory() + "/" + "Pixiedoo" + "/";
mCurrent = "Aura.png";
prepareDirectory();
compositeImageView = (ImageView) this
.findViewById(R.id.CompositeImageView);
choosePicture1 = (Button) this.findViewById(R.id.ChoosePictureButton1);
choosePicture2 = (Button) this.findViewById(R.id.ChoosePictureButton2);
choosePicture1.setOnClickListener(this);
choosePicture2.setOnClickListener(this);
save.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
Log.v(TAG, "Save Tab Clicked");
try {
mBitmapDrawable = new BitmapDrawable(drawingBitmap);
mNewSaving = ((BitmapDrawable) mBitmapDrawable).getBitmap();
String FtoSave = mTempDir + mCurrent;
File mFile = new File(FtoSave);
mFileOutputStream = new FileOutputStream(mFile);
mNewSaving.compress(CompressFormat.PNG, 95, mFileOutputStream);
mFileOutputStream.flush();
mFileOutputStream.close();
} catch (FileNotFoundException e) {
Log.v(TAG, "FileNotFoundExceptionError " + e.toString());
} catch (IOException e) {
Log.v(TAG, "IOExceptionError " + e.toString());
}
}
});
}
private boolean prepareDirectory() {
try {
if (makeDirectory()) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
//Toast.makeText(this, getString(R.string.sdcard_error), 1000).show();
return false;
}
}
private boolean makeDirectory() {
File mTempFile = new File(mTempDir);
if (!mTempFile.exists()) {
mTempFile.mkdirs();
}
if (mTempFile.isDirectory()) {
File[] mFiles = mTempFile.listFiles();
for (File mEveryFile : mFiles) {
if (!mEveryFile.delete()) {
//System.out.println(getString(R.string.failed_to_delete) + mEveryFile);
}
}
}
return (mTempFile.isDirectory());
}
public void onClick(View v) {
int which = -1;
if (v == choosePicture1) {
which = PICKED_ONE;
} else if (v == choosePicture2) {
which = PICKED_TWO;
}
Intent choosePictureIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(choosePictureIntent, which);
}
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK) {
Uri imageFileUri = intent.getData();
if (requestCode == PICKED_ONE) {
bmp1 = loadBitmap(imageFileUri);
onePicked = true;
} else if (requestCode == PICKED_TWO) {
bmp2 = loadBitmap(imageFileUri);
twoPicked = true;
}
if (onePicked && twoPicked) {
drawingBitmap = Bitmap.createBitmap(bmp1.getWidth(),
bmp1.getHeight(), bmp1.getConfig());
canvas = new Canvas(drawingBitmap);
paint = new Paint();
canvas.drawBitmap(bmp1, 90, 0, paint);
// paint.setXfermode(new PorterDuffXfermode(
// android.graphics.PorterDuff.Mode.MULTIPLY));
canvas.drawBitmap(bmp2, 30, 40, paint);
compositeImageView.setImageBitmap(drawingBitmap);
}
}
}
private Bitmap loadBitmap(Uri imageFileUri) {
Display currentDisplay = getWindowManager().getDefaultDisplay();
float dw = currentDisplay.getWidth();
float dh = currentDisplay.getHeight();
returnBmp = Bitmap.createBitmap((int) dw, (int) dh,
Bitmap.Config.ARGB_8888);
try {
// Load up the image's dimensions not the image itself
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
returnBmp = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(imageFileUri), null, bmpFactoryOptions);
int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / dh);
int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / dw);
Log.v("HEIGHTRATIO", "" + heightRatio);
Log.v("WIDTHRATIO", "" + widthRatio);
// If both of the ratios are greater than 1, one of the sides of the
// image is greater than the screen
if (heightRatio > 1 && widthRatio > 1) {
if (heightRatio > widthRatio) {
// Height ratio is larger, scale according to it
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
// Width ratio is larger, scale according to it
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
// Decode it for real
bmpFactoryOptions.inJustDecodeBounds = false;
returnBmp = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(imageFileUri), null, bmpFactoryOptions);
} catch (FileNotFoundException e) {
Log.v("ERROR", e.toString());
}
return returnBmp;
}
}
Related
This question already has answers here:
Capture Image from Camera and Display in Activity
(19 answers)
Closed 5 years ago.
I am new to android pls help me with it. Much appreciated. The problem is that, i get the image from camera, after it is being captured it will be display in the Imageview by getting captured image URL. however, when the image is display in the Imageview, the image is not of its actual size, it shrinks significantly. Could anyone help me with it, please.
The following is the code for cameraActivity:
public class CameraActivity extends AppCompatActivity {
Integer REQUEST_CAMERA =1, GALLERY_KITKAT_INTENT_CALLED=0;
public ImageView capturedPhoto;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_camera);
SelectImage();
capturedPhoto = (ImageView) findViewById(R.id.cameraPhoto);
}
private void SelectImage()
{
final CharSequence[] items ={"Camera","Gallery","Cancel"};
AlertDialog.Builder builder = new AlertDialog.Builder(CameraActivity.this);
builder.setTitle("Add Image");
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialogInterface, int i) {
if (items[i].equals("Camera")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, REQUEST_CAMERA);
//dispatchTakePictureIntent();
} else if (items[i].equals("Gallery")) {
Intent intent2 = new Intent(Intent.ACTION_OPEN_DOCUMENT);
intent2.addCategory(Intent.CATEGORY_OPENABLE);
intent2.setType("image/*");
startActivityForResult(intent2, GALLERY_KITKAT_INTENT_CALLED);
} else if (items[i].equals("Cancel")) {
dialogInterface.dismiss();
}
}
});
builder.show();
}
#Override
public void onActivityResult(int requestCode,int resultCode, Intent data)
{
super.onActivityResult(requestCode,resultCode,data);
if(resultCode == Activity.RESULT_OK && requestCode == REQUEST_CAMERA)
{
Bitmap image =(Bitmap) data.getExtras().get("data");
capturedPhoto.setImageBitmap(image);
//call to get uri from bitmap
Uri tempUri = getImageUri(getApplicationContext(),image);
//call to get actual path
//Toast.makeText(CameraActivity.this,"Here"+getRealPathFromURI(tempUri),Toast.LENGTH_SHORT).show();
GlobalVariables.filepath=getRealPathFromURI(tempUri);
setContentView(new SomeView(CameraActivity.this));
}
if (requestCode == GALLERY_KITKAT_INTENT_CALLED && resultCode == RESULT_OK && null != data )
{
if (requestCode == GALLERY_KITKAT_INTENT_CALLED) {
String filepath2 = "";
Uri originalUri = null;
originalUri = data.getData();
final int takeFlags = data.getFlags()
& (Intent.FLAG_GRANT_READ_URI_PERMISSION | Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
// Check for the freshest data.
getContentResolver().takePersistableUriPermission(originalUri,
takeFlags);
filepath2 = getPath(originalUri);
if (filepath2.toString() != null) {
// LoadPicture(filepath);
GlobalVariables.filepath = filepath2;
// cropImageView.setVisibility(View.VISIBLE);
setContentView(new SomeView(CameraActivity.this));
}
}
}
}
#SuppressLint("NewApi")
private String getPath(Uri uri) {
if (uri == null) {
return null;
}
String[] projection = {MediaStore.Images.Media.DATA};
Cursor cursor;
if (Build.VERSION.SDK_INT > 19) {
// Will return "image:x*"
String wholeID = DocumentsContract.getDocumentId(uri);
// Split at colon, use second item in the array
String id = wholeID.split(":")[1];
// where id is equal to
String sel = MediaStore.Images.Media._ID + "=?";
cursor = getContentResolver().query(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI, projection,
sel, new String[]{id}, null);
} else {
cursor = getContentResolver().query(uri, projection, null, null,
null);
}
String path = null;
try {
int column_index = cursor
.getColumnIndex(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
path = cursor.getString(column_index).toString();
cursor.close();
} catch (NullPointerException e) {
}
return path;
}
public Uri getImageUri(Context inContext, Bitmap image )
{
//ByteArrayOutputStream bytes = new ByteArrayOutputStream();
//thumbnail.compress(Bitmap.CompressFormat.JPEG,100,bytes);
String path = MediaStore.Images.Media.insertImage(inContext.getContentResolver(),image,"title",null);
return Uri.parse(path);
}
public String getRealPathFromURI(Uri uri)
{
Cursor cursor = getContentResolver().query(uri,null,null,null,null);
cursor.moveToFirst();
int idx=cursor.getColumnIndex(MediaStore.Images.ImageColumns.DATA);
return cursor.getString(idx);
}
}
The following is the xml file:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout 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"
tools:context="com.mbdp.w.areametric.CameraActivity">
<ImageView
android:id="#+id/cameraPhoto"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</RelativeLayout>
This is the code for SomeView class:
public class SomeView extends View implements View.OnTouchListener{
private Paint paint;
public static List<Point> points;
int DIST = 2;
boolean flgPathDraw = true;
String filepath = GlobalVariables.filepath;
Point mfirstpoint = null;
boolean bfirstpoint = false;
Point mlastpoint = null;
Bitmap bitmap = scaleToActualAspectRatio(rotateBitmap(filepath,
BitmapFactory.decodeFile(filepath)));
Context mContext;
public SomeView(Context c) {
super(c);
Toast.makeText(getContext(), "Crop the coin on image", Toast.LENGTH_LONG)
.show();
mContext = c;
setFocusable(true);
setFocusableInTouchMode(true);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setPathEffect(new DashPathEffect(new float[]{10, 20}, 0));
paint.setStrokeWidth(5);
paint.setColor(Color.WHITE);
this.setOnTouchListener(this);
points = new ArrayList<Point>();
bfirstpoint = false;
}
public SomeView(Context context, AttributeSet attrs) {
super(context, attrs);
mContext = context;
setFocusable(true);
setFocusableInTouchMode(true);
paint = new Paint(Paint.ANTI_ALIAS_FLAG);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(2);
paint.setColor(Color.WHITE);
this.setOnTouchListener(this);
points = new ArrayList<Point>();
bfirstpoint = false;
}
public void onDraw(Canvas canvas) {
canvas.drawBitmap(bitmap, 0, 0, null);
Path path = new Path();
boolean first = true;
for (int i = 0; i < points.size(); i += 2) {
Point point = points.get(i);
if (first) {
first = false;
path.moveTo(point.x, point.y);
} else if (i < points.size() - 1) {
Point next = points.get(i + 1);
path.quadTo(point.x, point.y, next.x, next.y);
} else {
mlastpoint = points.get(i);
path.lineTo(point.x, point.y);
}
}
canvas.drawPath(path, paint);
}
public boolean onTouch(View view, MotionEvent event) {
Point point = new Point();
point.x = (int) event.getX();
point.y = (int) event.getY();
if (flgPathDraw) {
if (bfirstpoint) {
if (comparepoint(mfirstpoint, point)) {
// points.add(point);
points.add(mfirstpoint);
flgPathDraw = false;
showcropdialog();
} else {
points.add(point);
}
} else {
points.add(point);
}
if (!(bfirstpoint)) {
mfirstpoint = point;
bfirstpoint = true;
}
}
invalidate();
Log.e("Hi ==>", "Size: " + point.x + " " + point.y);
if (event.getAction() == MotionEvent.ACTION_UP) {
Log.d("Action up", "called");
mlastpoint = point;
if (flgPathDraw) {
if (points.size() > 12) {
if (!comparepoint(mfirstpoint, mlastpoint)) {
flgPathDraw = false;
points.add(mfirstpoint);
showcropdialog();
}
}
}
}
return true;
}
private boolean comparepoint(Point first, Point current) {
int left_range_x = (int) (current.x - 3);
int left_range_y = (int) (current.y - 3);
int right_range_x = (int) (current.x + 3);
int right_range_y = (int) (current.y + 3);
if ((left_range_x < first.x && first.x < right_range_x)
&& (left_range_y < first.y && first.y < right_range_y)) {
if (points.size() < 10) {
return false;
} else {
return true;
}
} else {
return false;
}
}
public void resetView() {
points.clear();
paint.setColor(Color.WHITE);
paint.setStyle(Paint.Style.STROKE);
flgPathDraw = true;
invalidate();
}
public Bitmap scaleToActualAspectRatio(Bitmap bitmap) {
if (bitmap != null) {
boolean flag = true;
DisplayMetrics metrics = Resources.getSystem().getDisplayMetrics();
int deviceWidth = metrics.widthPixels;
int deviceHeight = metrics.heightPixels;
Matrix matrix = new Matrix();
matrix.postRotate(90);
int bitmapHeight = bitmap.getHeight(); // 563
int bitmapWidth = bitmap.getWidth(); // 900
// aSCPECT rATIO IS Always WIDTH x HEIGHT rEMEMMBER 1024 x 768
if (bitmapWidth > deviceWidth) {
flag = false;
// scale According to WIDTH
int scaledWidth = deviceWidth;
int scaledHeight = (scaledWidth * bitmapHeight) / bitmapWidth;
try {
if (scaledHeight > deviceHeight)
scaledHeight = deviceHeight;
bitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth,
scaledHeight, true);
} catch (Exception e) {
e.printStackTrace();
}
}
if (flag) {
if (bitmapHeight > deviceHeight) {
// scale According to HEIGHT
int scaledHeight = deviceHeight;
int scaledWidth = (scaledHeight * bitmapWidth)
/ bitmapHeight;
try {
if (scaledWidth > deviceWidth)
scaledWidth = deviceWidth;
bitmap = Bitmap.createScaledBitmap(bitmap, scaledWidth,
scaledHeight, true);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
return bitmap;
}
private void showcropdialog() {
DialogInterface.OnClickListener dialogClickListener = new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
Intent intent;
switch (which) {
case DialogInterface.BUTTON_NEUTRAL:
resetView();
break;
case DialogInterface.BUTTON_POSITIVE:
// Yes button clicked
// bfirstpoint = false;
intent = new Intent(mContext, CropActivity.class);
intent.putExtra("crop", true);
mContext.startActivity(intent);
break;
case DialogInterface.BUTTON_NEGATIVE:
// No button clicked
intent = new Intent(mContext, CropActivity.class);
intent.putExtra("crop", false);
mContext.startActivity(intent);
bfirstpoint = false;
// resetView();
break;
}
}
};
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
builder.setMessage("Please select Crop or Inverse crop")
.setNeutralButton("Re-Crop", dialogClickListener)
.setPositiveButton("Crop", dialogClickListener)
.setNegativeButton("Inverse Crop", dialogClickListener).show()
.setCancelable(false);
}
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Handle the back button
if (keyCode == KeyEvent.KEYCODE_BACK) {
// Ask the user if they want to quit
// restart app
Intent i = getContext().getPackageManager()
.getLaunchIntentForPackage(getContext().getPackageName());
i.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
// startActionMode(i);
SomeView.this.getContext().startActivity(i);
return true;
} else {
return super.onKeyDown(keyCode, event);
}
}
public static Bitmap rotateBitmap(String src, Bitmap bitmap) {
try {
int orientation = getExifOrientation(src);
if (orientation == 1) {
return bitmap;
}
Matrix matrix = new Matrix();
switch (orientation) {
case 2:
matrix.setScale(-1, 1);
break;
case 3:
matrix.setRotate(180);
break;
case 4:
matrix.setRotate(180);
matrix.postScale(-1, 1);
break;
case 5:
matrix.setRotate(90);
matrix.postScale(-1, 1);
break;
case 6:
matrix.setRotate(90);
break;
case 7:
matrix.setRotate(-90);
matrix.postScale(-1, 1);
break;
case 8:
matrix.setRotate(-90);
break;
default:
return bitmap;
}
try {
Bitmap oriented = Bitmap.createBitmap(bitmap, 0, 0,
bitmap.getWidth(), bitmap.getHeight(), matrix, true);
bitmap.recycle();
return oriented;
} catch (OutOfMemoryError e) {
e.printStackTrace();
return bitmap;
}
} catch (IOException e) {
e.printStackTrace();
}
return bitmap;
}
private static int getExifOrientation(String src) throws IOException {
int orientation = 1;
try {
if (Build.VERSION.SDK_INT >= 5) {
Class<?> exifClass = Class
.forName("android.media.ExifInterface");
Constructor<?> exifConstructor = exifClass
.getConstructor(new Class[]{String.class});
Object exifInstance = exifConstructor
.newInstance(new Object[]{src});
Method getAttributeInt = exifClass.getMethod("getAttributeInt",
new Class[]{String.class, int.class});
Field tagOrientationField = exifClass
.getField("TAG_ORIENTATION");
String tagOrientation = (String) tagOrientationField.get(null);
orientation = (Integer) getAttributeInt.invoke(exifInstance,
new Object[]{tagOrientation, 1});
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SecurityException e) {
e.printStackTrace();
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (IllegalArgumentException e) {
e.printStackTrace();
} catch (InstantiationException e) {
e.printStackTrace();
} catch (IllegalAccessException e) {
e.printStackTrace();
} catch (InvocationTargetException e) {
e.printStackTrace();
} catch (NoSuchFieldException e) {
e.printStackTrace();
}
return orientation;
}
}
Links to image of what happened:
Actual image on camera
Displayed image in ImageView gets shrink
That small image from camera indicates thumbnail since you use reading bitmap from extra..
This example will help you get full image:
How to capture an image and store it with the native Android Camera
my apps have feature set photo profile, but when upload an image from gallery to server the image automatic rotated 90 degree, this issue appear only for portrait image, in landscape image running well, I already add crop feature but it doesn't help, here is my code to update profile image:
private void updateProfile(){
// multipart
MultipartBody.Part _file = null;
if(proPicPath != null){
// ini progress listener
ProgressRequestBody.ProgressListener progressListener = new ProgressRequestBody.ProgressListener() {
#Override
public void transferred(final int num, long transferred, long totalSize) {
Handler handler = new Handler(Looper.getMainLooper());
handler.post(new Runnable() {
#Override
public void run() {
try {
dialogUpload.setMessage("Updating "+ num + "%");
}catch (NullPointerException ne){
ne.printStackTrace();
}
}
});
}
};
File file = new File(proPicPath);
// init request body
ProgressRequestBody requestFileBody = new ProgressRequestBody(file, "multipart/form-data", progressListener);
_file = MultipartBody.Part.createFormData("caller_pic", file.getName(), requestFileBody);
}
// set request body
RequestBody _caller_id = RequestBody.create(MediaType.parse("text/plain"), own.caller_id);
RequestBody _name = null;
if(!etUserName.getText().toString().isEmpty())
_name = RequestBody.create(MediaType.parse("text/plain"), etUserName.getText().toString());
RequestBody _email = null;
if(!etUserEmail.getText().toString().isEmpty())
_email = RequestBody.create(MediaType.parse("text/plain"), etUserEmail.getText().toString());
Call<APIResponse<ContactItem>> call = ServicesFactory.getService().updateProfile(_caller_id, _name, _email, _file);
call.enqueue(new Callback<APIResponse<ContactItem>>() {
#Override
public void onResponse(Call<APIResponse<ContactItem>> call, Response<APIResponse<ContactItem>> response) {
dialogUpload.dismiss();
dialogUpload = null;
if(response.isSuccessful() && response.body().isSuccessful()){
proPicPath = null;
ContactItem updated = response.body().data;
// save to session and update local variable
own = SessionManager.saveProfile(ProfileActivity.this, updated);
// update ui
setUserInfo();
checkProfileChanged();
toast("Update profile success");
}
else{
toast("Update profile failed");
}
}
#Override
public void onFailure(Call<APIResponse<ContactItem>> call, Throwable t) {
dialogUpload.dismiss();
dialogUpload = null;
toast("Update profile failed");
}
});
}
I got exactly the same issue, I solve it with this :
int IMAGE_UPLOAD_MAX_COMPRESSION = 75;
Bitmap mSelectedImage;
try {
mSelectedImage = MediaStore.Images.Media.getBitmap(this.getContentResolver(), Uri.parse("file:" + mCurrentPhotoPath));
mSelectedImage = PictureOrientation.bitmapFromUri(EditProfileActivity.this, Uri.parse("file:" + mCurrentPhotoPath));
OutputStream os = new FileOutputStream(mCurrentPhotoPath);
mSelectedImage.compress(Bitmap.CompressFormat.JPEG, IMAGE_UPLOAD_MAX_COMPRESSION, os);
os.flush();
os.close();
} catch (Exception ex) {
ex.printStackTrace();
}
The interesting part for you is here
PictureOrientation.bitmapFromUri(EditProfileActivity.this, Uri.parse("file:" + mCurrentPhotoPath));
This is the PictureOrientation class :
public class PictureOrientation {
public static Bitmap bitmapFromUri(Context context, Uri photoUri)
throws FileNotFoundException, IOException {
InputStream is = context.getContentResolver().openInputStream(photoUri);
BitmapFactory.Options dbo = new BitmapFactory.Options();
dbo.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, dbo);
is.close();
int rotatedWidth, rotatedHeight;
int orientation = 0;
if (photoUri.toString().contains("content:/")) {
orientation = getOrientation(context, photoUri);
} else {
int orientationFormExif = getOrientationFromExif(photoUri, context);
orientation = decodeExifOrientation(orientationFormExif);
}
if (orientation == 90 || orientation == 270) {
rotatedWidth = dbo.outHeight;
rotatedHeight = dbo.outWidth;
} else {
rotatedWidth = dbo.outWidth;
rotatedHeight = dbo.outHeight;
}
Bitmap srcBitmap = readScaledBitmapFromUri(photoUri, context,
rotatedWidth, rotatedHeight);
srcBitmap = setProperOrientation(orientation, srcBitmap);
return srcBitmap;
}
private static int getOrientation(Context context, Uri photoUri) {
/* it's on the external media. */
Cursor cursor = context.getContentResolver().query(photoUri,
new String[]{MediaStore.Images.ImageColumns.ORIENTATION},
null, null, null);
if (cursor.getCount() != 1) {
return -1;
}
cursor.moveToFirst();
return cursor.getInt(0);
}
private static int getOrientationFromExif(Uri imageUri, Context context) {
int orientation = -1;
File imageFile = new File(imageUri.getPath());
try {
ExifInterface exif;
exif = new ExifInterface(imageFile.getAbsolutePath());
orientation = exif.getAttributeInt(ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
} catch (IOException e) {
e.printStackTrace();
}
return orientation;
}
private static int decodeExifOrientation(int orientation) {
switch (orientation) {
case ExifInterface.ORIENTATION_NORMAL:
orientation = 0;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
orientation = 90;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
orientation = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_270:
orientation = 270;
break;
default:
break;
}
return orientation;
}
private static Bitmap readScaledBitmapFromUri(Uri photoUri, Context context, int width, int height)
throws FileNotFoundException, IOException {
InputStream is;
Bitmap srcBitmap;
is = context.getContentResolver().openInputStream(photoUri);
if (width > EditProfileActivity.IMAGE_WIDTH || height > EditProfileActivity.IMAGE_HEIGHT) {
float ratio = calculateScaleRatio(width, height);
srcBitmap = readRoughScaledBitmap(is, ratio);
ratio = calculateScaleRatio(srcBitmap.getWidth(),
srcBitmap.getHeight());
srcBitmap = scaleBitmap(srcBitmap, ratio);
} else {
srcBitmap = BitmapFactory.decodeStream(is);
}
is.close();
return srcBitmap;
}
private static float calculateScaleRatio(int width, int height) {
float widthRatio = ((float) width) / ((float) EditProfileActivity.IMAGE_WIDTH);
float heightRatio = ((float) height) / ((float) EditProfileActivity.IMAGE_HEIGHT);
float maxRatio = Math.max(widthRatio, heightRatio);
return maxRatio;
}
private static Bitmap readRoughScaledBitmap(InputStream is, float maxRatio) {
Bitmap result;
// Create the bitmap from file
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = (int) maxRatio;
result = BitmapFactory.decodeStream(is, null, options);
return result;
}
private static Bitmap scaleBitmap(Bitmap bitmap, float ratio) {
int width = bitmap.getWidth();
int height = bitmap.getHeight();
Matrix matrix = new Matrix();
matrix.postScale(1f / ratio, 1f / ratio);
Bitmap result = Bitmap.createBitmap(bitmap, 0, 0, width, height,
matrix, true);
return result;
}
private static Bitmap setProperOrientation(int orientation, Bitmap srcBitmap) {
if (orientation > 0) {
Matrix matrix = new Matrix();
matrix.postRotate(orientation);
srcBitmap = Bitmap.createBitmap(srcBitmap, 0, 0,
srcBitmap.getWidth(), srcBitmap.getHeight(), matrix, true);
}
return srcBitmap;
}
}
This class look the exif orientation of the picture and rotate it.
I have an overlay with one mask-able transparent area with the
x,y,width,height prams. i am taking one image from gallery and
placing that selected image at the Given x,y coordinates. This placing
is done in frame layout. Now i am able to rotate, zoom, move with in
that mask area. after i fitted into that mask are i want to get the
current x,y coordinates of the image with in the mask so that for
combining i am combining the image using canvas based on the x,y
position.presently i am taking the values using event.getx(), event.gety() in on touch .
if i draw using those positions mask image is not drawing at the correct
position after i zooming or moving
This is my code. Please help me if anyone have the idea.
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_crop);
mSelectedVersion = getIntent().getExtras().getInt(
CROP_VERSION_SELECTED_KEY, -1);
Object overLayPath = getIntent().getExtras().containsKey("overLayPath") ? getIntent()
.getExtras().get("overLayPath") : null;
className = getIntent().getExtras().containsKey("class") ? (String) getIntent()
.getExtras().get("class") : null;
pageCount = (int) (getIntent().getExtras().containsKey("pageCount") ? getIntent()
.getExtras().getInt("pageCount") : 0);
File file = new File(overLayPath.toString());
String imgFile = (String) getIntent().getExtras().get("bitmap");
metrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(metrics);
mScreenHeight = metrics.heightPixels;
mScreenWidth = metrics.widthPixels;
if (photoImg != null) {
photoImg.recycle();
photoImg = null;
}
if (className.equalsIgnoreCase("Fb_List")) {
if (imgFile != null && !imgFile.equalsIgnoreCase("")) {
File imageFile = new File(imgFile);
photoImg = BitmapFactory
.decodeFile(imageFile.getAbsolutePath());
}
} else {
if (imgFile != null && !imgFile.equalsIgnoreCase("")) {
Uri selectedImageURI = Uri.parse(imgFile);
InputStream is;
try {
is = getContentResolver().openInputStream(selectedImageURI);
if (photoImg != null) {
photoImg.recycle();
photoImg = null;
}
photoImg = decodeSampledBitmapFromResource(is,
(int) (320 * metrics.density),
(int) (416 * metrics.density));
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
mImg = (ImageView) findViewById(R.id.cp_img);
photoImg = createMaskImage(photoImg, mImg);
if (!file.exists()) {
bitmap = BitmapFactory.decodeResource(getResources(),
R.drawable.transparentoverlay);
} else {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
bitmap = BitmapFactory.decodeFile(overLayPath.toString(), options);
}
BitmapDrawable drawable = (BitmapDrawable) mImg.getDrawable();
if (drawable != null && drawable.getBitmap() != null) {
drawable.getBitmap().recycle();
mImg.setImageDrawable(null);
}
mTemplateImg = (ImageView) findViewById(R.id.cp_face_template);
mTemplateImg.setImageBitmap(bitmap);
mImg.setOnTouchListener(this);
if (mScreenWidth > 600 && mScreenHeight > 1024) {
bitmap = Bitmap.createScaledBitmap(bitmap,
(int) (320 * metrics.density),
(int) (416 * metrics.density), true);
mTemplateImg.setImageBitmap(bitmap);
} else if (mScreenWidth > 460 && mScreenHeight > 720) {
bitmap = Bitmap.createScaledBitmap(bitmap,
(int) (320 * metrics.density),
(int) (416 * metrics.density), true);
mTemplateImg.setImageBitmap(bitmap);
}
mImg.setImageBitmap(photoImg);
mMatrix.postScale(mScaleFactor, mScaleFactor);
mImg.setImageMatrix(mMatrix);
// Setup Gesture Detectors
mScaleDetector = new ScaleGestureDetector(getApplicationContext(),
new ScaleListener());
mRotateDetector = new RotateGestureDetector(getApplicationContext(),
new RotateListener());
mMoveDetector = new MoveGestureDetector(MaskCropActivity.this,
new MoveListener());
}
private Bitmap createMaskImage(Bitmap photoImg2, ImageView maskView) {
if (photoImg2 != null) {
String template = Common.getPrefrenceValue(
Constants.TEMPLATE_OBJECT, MaskCropActivity.this);
JSONObject templateObject = null;
if (template != null && !template.equalsIgnoreCase("")) {
try {
templateObject = new JSONObject(template);
JSONArray pageDetails = templateObject
.getJSONArray("pageDetails");
JSONObject pageObject = pageDetails
.getJSONObject(pageCount - 1);
JSONArray maskImages;
maskImages = pageObject.getJSONArray("maskImages");
if (maskImages != null && maskImages.length() > 0) {
JSONObject maskObject = maskImages.getJSONObject(0);
String coOrdinates = maskObject.has("coOrdinates") ? maskObject
.getString("coOrdinates") : "";
if (coOrdinates.contains(",")
&& coOrdinates.split(",").length == 4) {
int x = Integer.parseInt(coOrdinates.split(",")[0]);
int y = Integer.parseInt(coOrdinates.split(",")[1]);
maskX = x;
maskY = y;
int width = Integer
.parseInt(coOrdinates.split(",")[2]);
int height = Integer.parseInt(coOrdinates
.split(",")[3]);
if (width != 0 && height != 0) {
if (((photoImg2.getWidth() - (int) (width * metrics.density)) / 2)
+ (int) (width * metrics.density) > photoImg2
.getWidth()
|| (50 + (int) (height * metrics.density)) > photoImg2
.getHeight()) {
Log.i(TAG,
"image size is less than required");
photoImg2 = Bitmap.createScaledBitmap(
photoImg2,
(int) (width * metrics.density),
(int) (height * metrics.density),
true);
} else {
Log.i(TAG,
"image size is more than required");
photoImg2 = Bitmap
.createBitmap(
photoImg2,
(photoImg2.getWidth() - (int) (width * metrics.density)) / 2,
50,
(int) (width * metrics.density),
(int) (height * metrics.density));
}
}
MarginLayoutParams mlp = (MarginLayoutParams) maskView
.getLayoutParams();
mlp.setMargins(x, y, 0, 0);// all in pixels
maskView.setLayoutParams(mlp);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return photoImg2;
}
return photoImg2;
}
public static Bitmap decodeSampledBitmapFromResource(
InputStream inputStream, int reqWidth, int reqHeight) {
byte[] byteArr = new byte[0];
byte[] buffer = new byte[1024];
int len;
int count = 0;
try {
while ((len = inputStream.read(buffer)) > -1) {
if (len != 0) {
if (count + len > byteArr.length) {
byte[] newbuf = new byte[(count + len) * 2];
System.arraycopy(byteArr, 0, newbuf, 0, count);
byteArr = newbuf;
}
System.arraycopy(buffer, 0, byteArr, count, len);
count += len;
}
}
final BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(byteArr, 0, count, options);
options.inSampleSize = calculateInSampleSize(options, reqWidth,
reqHeight);
options.inPurgeable = true;
options.inInputShareable = true;
options.inJustDecodeBounds = false;
options.inPreferredConfig = Bitmap.Config.ARGB_8888;
int[] pids = { android.os.Process.myPid() };
return BitmapFactory.decodeByteArray(byteArr, 0, count, options);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public void onCropImageButton(View v) {
// Create progress dialog and display it.
try {
mProgressDialog = new ProgressDialog(v.getContext());
mProgressDialog.setCancelable(false);
mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
mProgressDialog.setMessage("Cropping Image\nPlease Wait.....");
mProgressDialog.show();
} catch (Exception e) {
e.printStackTrace();
}
// Setting values so that we can retrive the image from
// ImageView multiple times.
mImg.buildDrawingCache(true);
mImg.setDrawingCacheEnabled(true);
mTemplateImg.buildDrawingCache(true);
mTemplateImg.setDrawingCacheEnabled(true);
// Create new thread to crop.
new Thread(new Runnable() {
#Override
public void run() {
if (mSelectedVersion == VERSION_1) {
croppedImg = cropImage(photoImg, bitmap);
Common common = new Common();
if (className.equalsIgnoreCase("Fb_List")) {
storeImage(croppedImg, "overlay" + pageCount + ".png");
} else {
Common.storeCropImage(croppedImg, "overlay1.png",
MaskCropActivity.this);
photoImg.recycle();
}
} /*
* else { croppedImg = ImageProcess.cropImageVer2(
* mImg.getDrawingCache(true),
* mTemplateImg.getDrawingCache(true), 320, 440); }
*/
// }
try {
mProgressDialog.dismiss();
} catch (Exception e) {
// TODO: handle exception
}
mImg.setDrawingCacheEnabled(false);
mTemplateImg.setDrawingCacheEnabled(false);
}
}).start();
}
private boolean storeImage(Bitmap imageData, String filename) {
String iconsStoragePath = Common.SDCARD_PATH
+ Common.UNZIPPED_PATH
+ Common.getPrefrenceValue(Constants.ZIPFILE_NAME,
MaskCropActivity.this) + "/custom";
File sdIconStorageDir = new File(iconsStoragePath);
sdIconStorageDir.mkdirs();
try {
String filePath = sdIconStorageDir.toString() + "/" + filename;
FileOutputStream fileOutputStream = new FileOutputStream(filePath);
BufferedOutputStream bos = new BufferedOutputStream(
fileOutputStream);
System.out.println("imageData" + imageData);
imageData.compress(CompressFormat.PNG, 90, bos);
Intent intent = new Intent(MaskCropActivity.this,
DesignPriviewEditing.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
finish();
bos.flush();
bos.close();
} catch (FileNotFoundException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}
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) {
final int halfHeight = height / 2;
final int halfWidth = width / 2;
while ((halfHeight / inSampleSize) > reqHeight
&& (halfWidth / inSampleSize) > reqWidth) {
inSampleSize *= 2;
}
}
return inSampleSize;
}
public boolean onTouch(View v, MotionEvent event) {
mScaleDetector.onTouchEvent(event);
mRotateDetector.onTouchEvent(event);
mMoveDetector.onTouchEvent(event);
float scaledImageCenterX = (mImageWidth * mScaleFactor) / 2;
float scaledImageCenterY = (mImageHeight * mScaleFactor) / 2;
mMatrix.reset();
mMatrix.postScale(mScaleFactor, mScaleFactor);
mMatrix.postRotate(mRotationDegrees, scaledImageCenterX,
scaledImageCenterY);
mMatrix.postTranslate(mFocusX - scaledImageCenterX, mFocusY
- scaledImageCenterY);
float[] values = new float[9];
mMatrix.getValues(values);
relativeX = (int) event.getX();
relativeY = (int) event.getY();
ImageView view = (ImageView) v;
view.setImageMatrix(mMatrix);
return true;
}
private class ScaleListener extends
ScaleGestureDetector.SimpleOnScaleGestureListener {
#Override
public boolean onScale(ScaleGestureDetector detector) {
mScaleFactor *= detector.getScaleFactor();
mScaleFactor = Math.max(0.1f, Math.min(mScaleFactor, 10.0f));
return true;
}
}
private class RotateListener extends
RotateGestureDetector.SimpleOnRotateGestureListener {
#Override
public boolean onRotate(RotateGestureDetector detector) {
mRotationDegrees -= detector.getRotationDegreesDelta();
return true;
}
}
private class MoveListener extends
MoveGestureDetector.SimpleOnMoveGestureListener {
#Override
public boolean onMove(MoveGestureDetector detector) {
PointF d = detector.getFocusDelta();
mFocusX += d.x;
mFocusY += d.y;
System.out.println("ON MOVE LISTSNER" + mFocusX + "MFOCUS Y"
+ mFocusY);
return true;
}
}
#Override
public void onBackPressed() {
Intent intent = new Intent(MaskCropActivity.this,
CropImagesActivity.class);
System.out
.println("pageCount in mASK CROP ON BACK PRESSED" + pageCount);
intent.putExtra("pageCount", pageCount);
startActivity(intent);
finish();
}
public Bitmap cropImage(Bitmap img, Bitmap templateImage) {
Bitmap bm = Bitmap.createBitmap((int) (320 * metrics.density),
(int) (416 * metrics.density), Bitmap.Config.ARGB_8888);
Canvas combineImg = new Canvas(bm);
combineImg.drawBitmap(img, relativeX, relativeY, null);
combineImg.drawBitmap(templateImage, 0, 0, null);
return bm;
}
I have this multiple image in a canvas, how do I get the anchors of each image in the canvas and be able to drag, resize and move it on the canvas.
heres the code.
public class MainActivity extends Activity implements OnClickListener {
static final int PICKED_ONE = 0;
static final int PICKED_TWO = 1;
boolean onePicked = false;
boolean twoPicked = false;
Button choosePicture1, choosePicture2;
ImageView compositeImageView;
Bitmap bmp1, bmp2;
Bitmap returnBmp;
Bitmap drawingBitmap;
Canvas canvas;
Paint paint;
protected static final String TAG = MainActivity.class.getName();
Bitmap mBackImage, mTopImage, mBackground, mInnerImage, mNewSaving;
Canvas mComboImage;
FileOutputStream mFileOutputStream;
BitmapDrawable mBitmapDrawable;
private String mCurrent = null;
private static String mTempDir;
Button save;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
save = (Button)findViewById(R.id.save);
mTempDir = Environment.getExternalStorageDirectory() + "/" + "Pixiedoo" + "/";
mCurrent = "Aura.png";
prepareDirectory();
compositeImageView = (ImageView) this
.findViewById(R.id.CompositeImageView);
choosePicture1 = (Button) this.findViewById(R.id.ChoosePictureButton1);
choosePicture2 = (Button) this.findViewById(R.id.ChoosePictureButton2);
choosePicture1.setOnClickListener(this);
choosePicture2.setOnClickListener(this);
save.setOnClickListener(new View.OnClickListener() {
#SuppressWarnings("deprecation")
public void onClick(View v) {
Log.v(TAG, "Save Tab Clicked");
try {
mBitmapDrawable = new BitmapDrawable(drawingBitmap);
mNewSaving = ((BitmapDrawable) mBitmapDrawable).getBitmap();
String FtoSave = mTempDir + mCurrent;
File mFile = new File(FtoSave);
mFileOutputStream = new FileOutputStream(mFile);
mNewSaving.compress(CompressFormat.PNG, 95, mFileOutputStream);
mFileOutputStream.flush();
mFileOutputStream.close();
} catch (FileNotFoundException e) {
Log.v(TAG, "FileNotFoundExceptionError " + e.toString());
} catch (IOException e) {
Log.v(TAG, "IOExceptionError " + e.toString());
}
}
});
}
private boolean prepareDirectory() {
try {
if (makeDirectory()) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
//Toast.makeText(this, getString(R.string.sdcard_error), 1000).show();
return false;
}
}
private boolean makeDirectory() {
File mTempFile = new File(mTempDir);
if (!mTempFile.exists()) {
mTempFile.mkdirs();
}
if (mTempFile.isDirectory()) {
File[] mFiles = mTempFile.listFiles();
for (File mEveryFile : mFiles) {
if (!mEveryFile.delete()) {
//System.out.println(getString(R.string.failed_to_delete) + mEveryFile);
}
}
}
return (mTempFile.isDirectory());
}
public void onClick(View v) {
int which = -1;
if (v == choosePicture1) {
which = PICKED_ONE;
} else if (v == choosePicture2) {
which = PICKED_TWO;
}
Intent choosePictureIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(choosePictureIntent, which);
}
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK) {
Uri imageFileUri = intent.getData();
if (requestCode == PICKED_ONE) {
bmp1 = loadBitmap(imageFileUri);
onePicked = true;
} else if (requestCode == PICKED_TWO) {
bmp2 = loadBitmap(imageFileUri);
twoPicked = true;
}
if (onePicked && twoPicked) {
drawingBitmap = Bitmap.createBitmap(bmp1.getWidth(),
bmp1.getHeight(), bmp1.getConfig());
canvas = new Canvas(drawingBitmap);
paint = new Paint();
canvas.drawBitmap(bmp1, 90, 0, paint);
// paint.setXfermode(new PorterDuffXfermode(
// android.graphics.PorterDuff.Mode.MULTIPLY));
canvas.drawBitmap(bmp2, 30, 40, paint);
compositeImageView.setImageBitmap(drawingBitmap);
}
}
}
private Bitmap loadBitmap(Uri imageFileUri) {
Display currentDisplay = getWindowManager().getDefaultDisplay();
float dw = currentDisplay.getWidth();
float dh = currentDisplay.getHeight();
returnBmp = Bitmap.createBitmap((int) dw, (int) dh,
Bitmap.Config.ARGB_8888);
try {
// Load up the image's dimensions not the image itself
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
returnBmp = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(imageFileUri), null, bmpFactoryOptions);
int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / dh);
int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / dw);
Log.v("HEIGHTRATIO", "" + heightRatio);
Log.v("WIDTHRATIO", "" + widthRatio);
// If both of the ratios are greater than 1, one of the sides of the
// image is greater than the screen
if (heightRatio > 1 && widthRatio > 1) {
if (heightRatio > widthRatio) {
// Height ratio is larger, scale according to it
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
// Width ratio is larger, scale according to it
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
// Decode it for real
bmpFactoryOptions.inJustDecodeBounds = false;
returnBmp = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(imageFileUri), null, bmpFactoryOptions);
} catch (FileNotFoundException e) {
Log.v("ERROR", e.toString());
}
return returnBmp;
}
}
I am having code for combining two image and show them together in a canvas as follows. Can you say how to store that as a single image.
public class ChoosePictureComposite extends Activity implements OnClickListener {
static final int PICKED_ONE = 0;
static final int PICKED_TWO = 1;
boolean onePicked = false;
boolean twoPicked = false;
Button choosePicture1, choosePicture2;
ImageView compositeImageView;
Bitmap bmp1, bmp2;
Canvas canvas;
Paint paint;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
compositeImageView = (ImageView) this
.findViewById(R.id.CompositeImageView);
choosePicture1 = (Button) this.findViewById(R.id.ChoosePictureButton1);
choosePicture2 = (Button) this.findViewById(R.id.ChoosePictureButton2);
choosePicture1.setOnClickListener(this);
choosePicture2.setOnClickListener(this);
}
public void onClick(View v) {
int which = -1;
if (v == choosePicture1) {
which = PICKED_ONE;
} else if (v == choosePicture2) {
which = PICKED_TWO;
}
Intent choosePictureIntent = new Intent(Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(choosePictureIntent, which);
}
protected void onActivityResult(int requestCode, int resultCode,
Intent intent) {
super.onActivityResult(requestCode, resultCode, intent);
if (resultCode == RESULT_OK) {
Uri imageFileUri = intent.getData();
if (requestCode == PICKED_ONE) {
bmp1 = loadBitmap(imageFileUri);
onePicked = true;
} else if (requestCode == PICKED_TWO) {
bmp2 = loadBitmap(imageFileUri);
twoPicked = true;
}
if (onePicked && twoPicked) {
Bitmap drawingBitmap = Bitmap.createBitmap(bmp1.getWidth(),
bmp1.getHeight(), bmp1.getConfig());
canvas = new Canvas(drawingBitmap);
paint = new Paint();
canvas.drawBitmap(bmp1, 90, 0, paint);
// paint.setXfermode(new PorterDuffXfermode(
// android.graphics.PorterDuff.Mode.MULTIPLY));
canvas.drawBitmap(bmp2, 30, 40, paint);
compositeImageView.setImageBitmap(drawingBitmap);
}
}
}
private Bitmap loadBitmap(Uri imageFileUri) {
Display currentDisplay = getWindowManager().getDefaultDisplay();
float dw = currentDisplay.getWidth();
float dh = currentDisplay.getHeight();
Bitmap returnBmp = Bitmap.createBitmap((int) dw, (int) dh,
Bitmap.Config.ARGB_4444);
try {
// Load up the image's dimensions not the image itself
BitmapFactory.Options bmpFactoryOptions = new BitmapFactory.Options();
bmpFactoryOptions.inJustDecodeBounds = true;
returnBmp = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(imageFileUri), null, bmpFactoryOptions);
int heightRatio = (int) Math.ceil(bmpFactoryOptions.outHeight / dh);
int widthRatio = (int) Math.ceil(bmpFactoryOptions.outWidth / dw);
Log.v("HEIGHTRATIO", "" + heightRatio);
Log.v("WIDTHRATIO", "" + widthRatio);
// If both of the ratios are greater than 1, one of the sides of the
// image is greater than the screen
if (heightRatio > 1 && widthRatio > 1) {
if (heightRatio > widthRatio) {
// Height ratio is larger, scale according to it
bmpFactoryOptions.inSampleSize = heightRatio;
} else {
// Width ratio is larger, scale according to it
bmpFactoryOptions.inSampleSize = widthRatio;
}
}
// Decode it for real
bmpFactoryOptions.inJustDecodeBounds = false;
returnBmp = BitmapFactory.decodeStream(getContentResolver()
.openInputStream(imageFileUri), null, bmpFactoryOptions);
} catch (FileNotFoundException e) {
Log.v("ERROR", e.toString());
}
return returnBmp;
}
}
Try this:
public class Aura extends Activity {
protected static final String TAG = Aura.class.getName();
private static String mTempDir;
Bitmap mBackImage, mTopImage, mBackground, mInnerImage, mNewSaving;
Canvas mComboImage;
FileOutputStream mFileOutputStream;
BitmapDrawable mBitmapDrawable;
private String mCurrent = null;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.aura);
mTempDir = Environment.getExternalStorageDirectory() + "/" + "Aura" + "/";
mCurrent = "Aura.png";
prepareDirectory();
mBackground = Bitmap.createBitmap(604, 1024, Bitmap.Config.ARGB_8888);
mBackImage = BitmapFactory.decodeResource(getResources(), R.drawable.aura);
mTopImage = BitmapFactory.decodeResource(getResources(), R.drawable.test);
mInnerImage = BitmapFactory.decodeResource(getResources(), R.drawable.anothertest);
mComboImage = new Canvas(mBackground);
mComboImage.drawBitmap(mBackImage, 0f, 0f, null);
mComboImage.drawBitmap(mTopImage, 0f, 0f, null);
mComboImage.drawBitmap(mInnerImage, 0f, 0f, null);
mFileOutputStream = null;
mSave.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Log.v(TAG, "Save Tab Clicked");
try {
mBitmapDrawable = new BitmapDrawable(mBackground);
mNewSaving = ((BitmapDrawable) mBitmapDrawable).getBitmap();
String FtoSave = mTempDir + mCurrent;
File mFile = new File(FtoSave);
mFileOutputStream = new FileOutputStream(mFile);
mNewSaving.compress(CompressFormat.PNG, 95, mFileOutputStream);
mFileOutputStream.flush();
mFileOutputStream.close();
} catch (FileNotFoundException e) {
Log.v(TAG, "FileNotFoundExceptionError " + e.toString());
} catch (IOException e) {
Log.v(TAG, "IOExceptionError " + e.toString());
}
}
});
}//onCreate
private boolean prepareDirectory() {
try {
if (makeDirectory()) {
return true;
} else {
return false;
}
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(this, getString(R.string.sdcard_error), 1000).show();
return false;
}
}
private boolean makeDirectory() {
File mTempFile = new File(mTempDir);
if (!mTempFile.exists()) {
mTempFile.mkdirs();
}
if (mTempFile.isDirectory()) {
File[] mFiles = mTempFile.listFiles();
for (File mEveryFile : mFiles) {
if (!mEveryFile.delete()) {
System.out.println(getString(R.string.failed_to_delete) + mEveryFile);
}
}
}
return (mTempFile.isDirectory());
}
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
if ((!(android.os.Build.VERSION.SDK_INT > android.os.Build.VERSION_CODES.DONUT)
&& keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0)) {
onBackPressed();
}
return super.onKeyDown(keyCode, event);
}
public void onBackPressed() {
finish();
}
}
create a new Bitmap with the height sum of the individual height of your images.
Bitmap newBitmap = Bitmap.createBitmap(widht
, totalHeight, Config.ARGB_8888);
Canvas canvas = new Canvas(newBitmap);
canvas.drawBitmap(image11, 0, 0, null);
canvas.drawBitmap(image2, 0, image1Height, null);
this should draw the 2 images into the newBitmap, one below the other. change height parameters to widht if you want them side by side.
Is this what you were looking for ?