Crop image and watermark it - java

I need to apply a watermark to a picture after it's been cropped, but something has gone wrong. My app takes a picture from the camera, launches a try to crop it and then applies a watermark.
This is how I save the picture after having taken it from the camera (not cropped.)
Uri uriSavedImage = null;
if (front) {
DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy");
Date date = new Date();
directory_path = date.toString();
directory = new File(Environment.getExternalStorageDirectory(), directory_path);
if (!directory.exists()) {
directory.mkdirs();
}
uriSavedImage = Uri.fromFile(new File(Environment.getExternalStorageDirectory()
+ "/"+ directory_path + "/front.jpg"));
OutputStream imageFileOS;
try {
imageFileOS = getContentResolver().openOutputStream( uriSavedImage);
imageFileOS.write(current_pics);
imageFileOS.flush();
imageFileOS.close();
runCropImage(uriSavedImage);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
This is the attempt to crop the image:
private void runCropImage(Uri pic_uri) {
Intent cropIntent = new Intent("com.android.camera.action.CROP");
cropIntent.setDataAndType(pic_uri, "image/*");
cropIntent.putExtra("crop", "true");
cropIntent.putExtra("aspectX", 1);
cropIntent.putExtra("aspectY", 1);
cropIntent.putExtra("outputX", 4800);
cropIntent.putExtra("outputY", 4800);
cropIntent.putExtra("return-data", true);
startActivityForResult(cropIntent, 2);
}
#Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == 2) {
if (data != null) {
String cropImagePath = null;
Bundle extras = data.getExtras();
Bitmap bitmap = (Bitmap) extras.get("data");
cropImagePath = Environment.getExternalStorageDirectory()
+ "/" + directory_path + "/front.jpg";
FileOutputStream out = null;
try {
out = new FileOutputStream(cropImagePath);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.flush();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
watermark(Uri.fromFile(new File(cropImagePath)), bitmap);
}
} else {
// TODO do nothing
}
}
}
This is how I apply the watermark:
public void watermark(Uri pic_uri, Bitmap bitmap) {
Bitmap src = BitmapFactory.decodeFile(pic_uri.getPath());
Bitmap result = Bitmap.createBitmap(1200, 1200, src.getConfig());
Canvas canvas = new Canvas(result);
canvas.drawBitmap(src, 0, 0, null);
Bitmap waterMark = BitmapFactory.decodeResource(getResources(),
R.drawable.watermark);
canvas.drawBitmap(waterMark, canvas.getWidth() - waterMark.getWidth(),
canvas.getHeight() - waterMark.getHeight(), null);
FileOutputStream out = null;
try {
out = new FileOutputStream(pic_uri.getPath());
result.compress(Bitmap.CompressFormat.JPEG, 80, out);
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
out.close();
} catch (Throwable ignore) {
}
}
}
The problem is that the watermark is applyed correctly, however the picture gets scaled!
So I have inside a new image, the cropped picture at the beginning of the picture (top left) and a watermark at the correct position (bottom left,) however the rest of picture is black.
So what's wrong?
The source cropped image has the correct dimension, 1200x1200 (verified by using a file manager), and the watermarked picture does too.
I've also tried to verify the dimension on "bitmap" object inside watermark function, but I got 300x300.
How can I solve this?

Related

Where to call Crop Image Before Setting to ImageView

Where to call Crop Image Before Setting to Image view as I'm not getting it as my Image not getting cropped for this activity. As I want to crop the Image and post the Cropped Image to the server as well
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == RESULT_OK) {
if (requestCode == 1) {
File f = new File(Environment.getExternalStorageDirectory().toString());
for (File temp : f.listFiles()) {
if (temp.getName().equals("temp.jpg")) {
f = temp;
break;
}
}
try {
Bitmap bitmap;
BitmapFactory.Options bitmapOptions = new BitmapFactory.Options();
bitmap = BitmapFactory.decodeFile(f.getAbsolutePath(),
bitmapOptions);
imgNavHeaderPic.setImageBitmap(bitmap);
String path = android.os.Environment
.getExternalStorageDirectory()
+ File.separator
+ "Phoenix" + File.separator + "default";
f.delete();
OutputStream outFile = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
createBitmapAndAssign(Uri.fromFile(file));
try {
outFile = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 85, outFile);
outFile.flush();
outFile.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
} else if (requestCode == 2) {
Uri selectedImage = data.getData();
createBitmapAndAssign(data.getData());
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
imgNavHeaderPic.setImageBitmap(thumbnail);
Drawable bitmap = imgNavHeaderPic.getDrawable();
}
}
}
As I'm also compressing my Image well...
try this one
try{
Bitmap bm = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
bm = Bitmap.createBitmap(bm, 0, 0, 400, 400);
your_imageview.setImageBitmap(bm);
}catch(Exception e){
e.printStackTrace();
}

Android Rotates Camera captured photo by itself

I would like to launch the native Android camera and save captured image at a specified location, but when I do that and i try to reach the photo later ,saved imaged is 90 degree rotated by itself. i am using a LG cellphone to run the program. I have been already tried a solution that i found here, but they did not work. I put my code for you here... please correct me or give me a new solution.
Thank you a lot
private void cameraIntent() {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
intent.putExtra("photo", true);
intent.putExtra("android.intent.extras.CAMERA_FACING", android.hardware.Camera.CameraInfo.CAMERA_FACING_FRONT);
intent.putExtra("android.intent.extras.LENS_FACING_FRONT", 1);
intent.putExtra("android.intent.extra.USE_FRONT_CAMERA", true);
startActivityForResult(intent, REQUEST_CAMERA);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (resultCode == Activity.RESULT_OK) {
if (requestCode == REQUEST_CAMERA)
onCaptureImageResult(data);
}
}
private void onCaptureImageResult(Intent data) {
ByteArrayOutputStream bytes = null;
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(getExternalStorageDirectory(),
File.separator + "profile.jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String address = getExternalStorageDirectory().getAbsolutePath();
ExifInterface exif = null;
try {
if(destination.exists()) {
exif = new ExifInterface(address+File.separator+"profile.jpg");
Log.d("EXIF value", exif.getAttribute(ExifInterface.TAG_ORIENTATION));
}
} catch (IOException e) {
e.printStackTrace();
}
if(exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("6")){
thumbnail= rotate(thumbnail, 90);
}else if(exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("8")){
thumbnail= rotate(thumbnail, 270);
}else if(exif.getAttribute(ExifInterface.TAG_ORIENTATION).equalsIgnoreCase("3")){
thumbnail= rotate(thumbnail, 270);
}
resized = Bitmap.createScaledBitmap(thumbnail, navUserImage.getWidth(), navUserImage.getHeight(), true);
navUserImage.setImageBitmap(resized);
}
It does not rotate in all devices. You can try this solution. I have worked on something similar, and it suited me well.

Screenshot Black in Android

I've been working out how to take a screenshot programmatically in android, however when it screenshots I get a toolbar and black screen captured instead of what is actually on the screen.
I've also tried to screenshot a particular TextView within the custom InfoWindow layout I created for the google map. But that creates a null pointer exception on the second line below.
TextView v1 = (TextView)findViewById(R.id.tv_code);
v1.setDrawingCacheEnabled(true);
Is there anyway to either actually screenshot what is on the screen without installing android screenshot library or to screenshot a TextView within a custom InfoWindow layout
This is my screenshot method:
/**
* Method to take a screenshot programmatically
*/
private void takeScreenshot(){
try {
//TextView I could screenshot instead of the whole screen:
//TextView v1 = (TextView)findViewById(R.id.tv_code);
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg");
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
MediaStore.Images.Media.insertImage(getContentResolver(), f.getAbsolutePath(), f.getName(), f.getName());
Log.d("debug", "Screenshot saved to gallery");
Toast.makeText(HuntActivity.this,"Code Saved!",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
EDIT: I have changed the method to the one provided from the source
How can i take/merge screen shot of Google map v2 and layout of xml both programmatically?
However it does not screenshot anything.
public void captureMapScreen() {
GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback() {
#Override
public void onSnapshotReady(Bitmap snapshot) {
try {
View mView = getWindow().getDecorView().getRootView();
mView.setDrawingCacheEnabled(true);
Bitmap backBitmap = mView.getDrawingCache();
Bitmap bmOverlay = Bitmap.createBitmap(
backBitmap.getWidth(), backBitmap.getHeight(),
backBitmap.getConfig());
Canvas canvas = new Canvas(bmOverlay);
canvas.drawBitmap(backBitmap, 0, 0, null);
canvas.drawBitmap(snapshot, new Matrix(), null);
FileOutputStream out = new FileOutputStream(
Environment.getExternalStorageDirectory()
+ "/"
+ System.currentTimeMillis() + ".jpg");
bmOverlay.compress(Bitmap.CompressFormat.JPEG, 90, out);
} catch (Exception e) {
e.printStackTrace();
}
}
};
mMap.snapshot(callback);
}
Use this code
private void takeScreenshot() {
AsyncTask<Void, Void, Void> asyc = new AsyncTask<Void, Void, Void>() {
#Override
protected void onPreExecute() {
super.onPreExecute();
objUsefullData.showProgress("Please wait", "");
}
#Override
protected Void doInBackground(Void... params) {
try {
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
bitmapscreen_shot = Bitmap.createBitmap(v1
.getDrawingCache());
v1.setDrawingCacheEnabled(false);
String state = Environment.getExternalStorageState();
File folder = null;
if (state.contains(Environment.MEDIA_MOUNTED)) {
folder = new File(
Environment.getExternalStorageDirectory()
+ "/piccapella");
} else {
folder = new File(
Environment.getExternalStorageDirectory()
+ "/piccapella");
}
boolean success = true;
if (!folder.exists()) {
success = folder.mkdirs();
}
if (success) {
// Create a media file name
String timeStamp = new SimpleDateFormat(
"yyyyMMdd_HHmmss", Locale.getDefault())
.format(new java.util.Date());
imageFile = new File(folder.getAbsolutePath()
+ File.separator + "IMG_" + timeStamp + ".jpg");
/*
* Toast.makeText(AddTextActivity.this,
* "saved Image path" + "" + imageFile,
* Toast.LENGTH_SHORT) .show();
*/
imageFile.createNewFile();
} else {
/*
* Toast.makeText(AddTextActivity.this,
* "Image Not saved", Toast.LENGTH_SHORT).show();
*/
}
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
// save image into gallery
bitmapscreen_shot.compress(CompressFormat.JPEG, 100,
ostream);
FileOutputStream fout = new FileOutputStream(imageFile);
fout.write(ostream.toByteArray());
fout.close();
Log.e("image_screen_shot", "" + imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
return null;
}
#Override
protected void onPostExecute(Void result) {
// TODO Auto-generated method stub
super.onPostExecute(result);
objUsefullData.dismissProgress();
}
};
asyc.execute();
}
Hope this will help you
I have figured it out !
/**
* Method to take a screenshot programmatically
*/
private void takeScreenshot(){
GoogleMap.SnapshotReadyCallback callback = new GoogleMap.SnapshotReadyCallback() {
#Override
public void onSnapshotReady(Bitmap bitmap) {
Bitmap b = bitmap;
String timeStamp = new SimpleDateFormat(
"yyyyMMdd_HHmmss", Locale.getDefault())
.format(new java.util.Date());
String filepath = timeStamp + ".jpg";
try{
OutputStream fout = null;
fout = openFileOutput(filepath,MODE_WORLD_READABLE);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, fout);
fout.flush();
fout.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
saveImage(filepath);
}
};
mMap.snapshot(callback);
}
/**
* Method to save the screenshot image
* #param filePath the file path
*/
public void saveImage(String filePath)
{
File file = this.getFileStreamPath(filePath);
if(!filePath.equals(""))
{
final ContentValues values = new ContentValues(2);
values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
values.put(MediaStore.Images.Media.DATA, file.getAbsolutePath());
final Uri contentUriFile = getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
Toast.makeText(HuntActivity.this,"Code Saved to files!",Toast.LENGTH_LONG).show();
}
else
{
System.out.println("ERROR");
}
}
I have adapted the code from this link so it doesn't share and instead just saves the image.
Capture screen shot of GoogleMap Android API V2
Thanks for everyones help
Please try with the code below:
private void takeScreenshot(){
try {
//TextView I could screenshot instead of the whole screen:
//TextView v1 = (TextView)findViewById(R.id.tv_code);
Bitmap bitmap = null;
Bitmap bitmap1 = null;
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
bitmap = Bitmap.createBitmap(v1.getDrawingCache());
try {
if (bitmap != null)
bitmap1 = Bitmap.createBitmap(bitmap, 0, 0,
v1.getWidth(), v1.getHeight());
} catch (OutOfMemoryError e) {
e.printStackTrace();
}
v1.setDrawingCacheEnabled(false);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap1.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg");
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
fo.flush();
fo.close();
MediaStore.Images.Media.insertImage(getContentResolver(), f.getAbsolutePath(), f.getName(), f.getName());
Log.d("debug", "Screenshot saved to gallery");
Toast.makeText(HuntActivity.this,"Code Saved!",Toast.LENGTH_LONG).show();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I faced this issue. After v1.setDrawingCacheEnabled(true); I added,
v1.buildDrawingCache();
And put some delay to call the takeScreenshot(); method.
It is fixed.

Add a watermark to photo before it's shared on social media

I've successfully added a watermark to the preview of the camera image that the user takes on my android app, however when it's sent to Instagram or Tumblr, the watermark isn't there.
I believe this is because it is sharing the image from local storage, and has nothing to do with the preview.
I think I need to modify the 'take picture' code for the camera, so that when it takes the photo it converts it to a bitmap, adds it to a canvas with the watermark and then saves it, but I'm not sure how to go about this.
I believe this is the source of the file being shared
final File fileToUpload = new File(StorageUtils.getStoragePath(ShareActivity.this), StorageUtils.DEFAULT_IMAGE);
Here is the take picture code for the camera.
protected void takePicture() {
if (cameraPreview == null) return;
Camera camera = cameraPreview.getCamera();
if (camera == null) return;
camera.takePicture(null, null, null, new Camera.PictureCallback() {
#Override
public void onPictureTaken(byte[] data, Camera camera) {
if (data == null || data.length == 0) return;
File imageFile = new File(StorageUtils.getStoragePath(CameraActivity.this), StorageUtils.DEFAULT_IMAGE);
File parentDir = imageFile.getParentFile();
if (!parentDir.exists()) {
if (!parentDir.mkdirs()) {
Log.d(TAG, "Failed to create directory: " + parentDir.getAbsolutePath());
return;
}
}
try {
FileOutputStream fos = new FileOutputStream(imageFile);
fos.write(data);
fos.close();
} catch (IOException e) {
Log.d(TAG, "Failed to save file: " + imageFile.getAbsolutePath());
e.printStackTrace();
return;
}
//workaround for bug with facing camera introduced (intentionally?) in 4.0+
if (isCameraFacingFront && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
Matrix matrix = new Matrix();
//flip image vertically
matrix.setRotate(180);
matrix.postScale(-1, 1);
Bitmap rotatedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
bitmap.recycle();
try {
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 80, new FileOutputStream(imageFile));
rotatedBitmap.recycle();
} catch (FileNotFoundException e) {
Log.d(TAG, "Failed to rotate and save bitmap: " + imageFile.getAbsolutePath());
e.printStackTrace();
return;
}
}
Intent intent = new Intent(CameraActivity.this, ShareActivity.class);
intent.putExtra(ShareActivity.PARAM_IMAGE_FILE, imageFile.getAbsolutePath());
if (business != null)
intent.putExtra(ShareActivity.PARAM_BUSINESS, business);
startActivity(intent);
}
});
}
Or I may be way off base. Any help or pointing in the right direction is much appreciated! Thank you!
Adding to my comment of, "You're on the right track. After you've gotten the picture, decode it, create a new Canvas for it, draw the watermark on the canvas, and save that image. You're pretty much just going to repeat the code for flipping the image, just drawing on the canvas right before saving the new image."...
I got bored and did it for you:
protected void takePicture() {
if (cameraPreview == null) return;
Camera camera = cameraPreview.getCamera();
if (camera == null) return;
camera.takePicture(null, null, null, new Camera.PictureCallback() {
public void onPictureTaken(byte[] data, Camera camera) {
File imageFile = new File(StorageUtils.getStoragePath(CameraActivity.this), StorageUtils.DEFAULT_IMAGE);
File parentDir = imageFile.getParentFile();
if(!createImageFromCamera(data, imageFile, parentDir) return;
//workaround for bug with facing camera introduced (intentionally?) in 4.0+
boolean requiresImageFlip = isCameraFacingFront && Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH;
Bitmap adjustedBitmap = getBitmap(imageFile, requiresImageFlip);
if(!drawWatermark(adjustedBitmap)) return;
if(!saveImage(imageFile, adjustedBitmap)) return;
Intent intent = new Intent(CameraActivity.this, ShareActivity.class);
intent.putExtra(ShareActivity.PARAM_IMAGE_FILE, imageFile.getAbsolutePath());
if(business != null) intent.putExtra(ShareActivity.PARAM_BUSINESS, business);
startActivity(intent);
}
});
}
private Bitmap getBitmap(File imageFile, boolean flipVertically){
Bitmap bitmap = BitmapFactory.decodeFile(imageFile.getAbsolutePath());
Matrix matrix = new Matrix();
if(flipVertically){
matrix.setRotate(180);
matrix.postScale(-1, 1);
}
Bitmap adjustedBitmap = Bitmap.createBitmap(bitmap, 0, 0, bitmap.getWidth(), bitmap.getHeight(), matrix, false);
bitmap.recycle();
return adjustedBitmap;
}
private boolean saveImage(File imageFile, Bitmap bitmap){
try {
bitmap.compress(Bitmap.CompressFormat.JPEG, 80, new FileOutputStream(imageFile));
bitmap.recycle();
return true;
}
catch (FileNotFoundException e) {
Log.d(TAG, "Failed to rotate and save bitmap: " + imageFile.getAbsolutePath());
e.printStackTrace();
return false;
}
}
private boolean drawWatermark(Bitmap bitmap){
try{
Canvas canvas = new Canvas(bitmap);
canvas.drawBitmap(watermarkBitmap); // However you're drawing the watermark on the canvas
return true;
}
catch(Exception e){
e.printStackTrace();
return false;
}
}
private boolean createImageFromCamera(byte[] data, File imageFile, File parentDir){
if (data == null || data.length == 0) return false;
if (!parentDir.exists()) {
if (!parentDir.mkdirs()) {
Log.d(TAG, "Failed to create directory: " + parentDir.getAbsolutePath());
return false;
}
}
try {
FileOutputStream fos = new FileOutputStream(imageFile);
fos.write(data);
fos.close();
}
catch (IOException e) {
Log.d(TAG, "Failed to save file: " + imageFile.getAbsolutePath());
e.printStackTrace();
return false;
}
return true;
}
Replace your entire takePicture() method with that and it should do everything you're looking for.

Android: Saving Picture to a File and Retrieving it

After taking a picture with my camera, I want to save it in that layout. I also want to save it to a File and be able to load that picture when I create the activity(so if i switch to a different activity and come back to this one). As of now, i can take the picture and display it, but if i switch activities more than once, the picture gets lost.I have the following relevant code:
I load my picture OnCreate using setImage():
private void setImage(){
if (loadPicture("hello", bitmap) != null) {
Toast.makeText(this, "not null", Toast.LENGTH_SHORT).show();
imageView.setImageBitmap(loadPicture("hello", bitmap));
}
}
private void takePicture(){
Intent intent = new Intent("android.media.action.IMAGE_CAPTURE");
File photo =
new File(Environment.getExternalStorageDirectory(), "Pic.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photo));
imageUri = Uri.fromFile(photo);
startActivityForResult(intent, 0);
}
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
Uri selectedImage = imageUri;
getContentResolver().notifyChange(selectedImage, null);
ContentResolver cr = getContentResolver();
try {
bitmap = android.provider.MediaStore.Images.Media
.getBitmap(cr, selectedImage);
imageView.setImageBitmap(Bitmap.createScaledBitmap(bitmap, bitmap.getHeight()/2, bitmap.getWidth()/2, false));
//**Where I save the picture**
savePicture("hello", bitmap, getApplicationContext());
}
private void savePicture(String filename, Bitmap b, Context ctx){
try {
ObjectOutputStream oos;
FileOutputStream out;// = new FileOutputStream(filename);
out = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
oos = new ObjectOutputStream(out);
b.compress(Bitmap.CompressFormat.PNG, 100, oos);
oos.close();
oos.notifyAll();
out.notifyAll();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
private Bitmap loadPicture(String filename, Bitmap b){
// Drawable myImage = null;
try {
FileInputStream fis = openFileInput(filename);
ObjectInputStream ois = null;
try {
ois = new ObjectInputStream(fis);
} catch (StreamCorruptedException e1) {
e1.printStackTrace();
} catch (IOException e1) {
e1.printStackTrace();
}
// myImage = Drawable.createFromStream(ois, filename);
b = BitmapFactory.decodeStream(ois);
try {
ois.close();
fis.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
// return myImage;
return b;
}
It sounds like your code works, but you are losing your image when the activity comes back. Loading your picture onPostResume() instead of onCreate() may be what you need. It feels like the activity lifecycle is the key to your problem. I have a couple of questions I will throw into comments.
out = ctx.openFileOutput(filename, Context.MODE_PRIVATE);
Try switching to:
out = ctx.openFileOutput(filename, Context.MODE_WORLD_READABLE);

Categories