I save a picture from imageView to SD. The image is saved.
The problem is that there is the first image, and saving the next image again saved the first with a different name.
As I understand need to catch the moment when the picture from imageView is loaded into playImage. But how to do it?
Thank's.
Load the image in imageView and save to sd:
public class Gallery extends Activity implements OnClickListener {
String item;
Button btnsave, btnhome;
ImageView playImage;
String fotoname;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.gallery);
btnhome = (Button) findViewById(R.id.btn_home);
btnhome.setOnClickListener(this);
btnsave = (Button)findViewById(R.id.btn_save);
btnsave.setOnClickListener(this);
playImage = (ImageView)findViewById(R.id.displayImage);
final ImageView playImage = (ImageView) findViewById(R.id.displayImage);
final LinearLayout myGallery = (LinearLayout) findViewById(R.id.mygallery1);
Bundle extras = getIntent().getExtras();
if(extras !=null) {
item = extras.getString("item");
if(item.equals("Item")){
try {
String galleryDirectoryName = "ITEM/item";
String[] listImages = getAssets().list(galleryDirectoryName);
for (String imageName : listImages) {
InputStream is = getAssets().open(galleryDirectoryName + "/" + imageName);
final Bitmap bitmap = BitmapFactory.decodeStream(is);
ImageView imageView = new ImageView(getApplicationContext());
imageView.setLayoutParams(new ViewGroup.LayoutParams(350, 225));
imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
imageView.setImageBitmap(bitmap);
imageView.setPadding(10, 70, 10, 70);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
playImage.setImageBitmap(bitmap);
playImage.setPadding(5, 0, 5, 0);
}
});
myGallery.addView(imageView);
}
} catch (IOException e) {
Log.e("GalleryWithHorizontalScrollView", e.getMessage(), e);
}
}
}
}
public void onClick(View v) {
// TODO Auto-generated method stub
switch(v.getId()){
case R.id.btn_save:
playImage.setDrawingCacheEnabled(true);
Bitmap bitmap = playImage.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/." + (getString(R.string.app_name)));
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "photo-"+ n +".jpg";
File file = new File (newDir, fotoname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
Toast.makeText(this, (getString(R.string.saved)), Toast.LENGTH_SHORT ).show();
} catch (Exception e) {
}
{
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(newDir, fotoname);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
this.sendBroadcast(mediaScanIntent);
}
break;
case R.id.btn_home:
finish();
}
}
}
Check this.
save.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
ll.setDrawingCacheEnabled(true);
Bitmap bitmap = ll.getDrawingCache();
// bitmap = Bitmap.createBitmap(480, 800,
// Bitmap.Config.ARGB_8888);
String root = Environment.getExternalStorageDirectory()
.toString();
File newDir = new File(root + "/Collage_Maker");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "cm_"+n + ".jpg";
File file = new File(newDir, fotoname);
String s = file.getAbsolutePath();
Log.i("Path of saved image.", s);
System.err.print("Path of saved image." + s);
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
Toast.makeText(getApplicationContext(), "Photo Saved "+ fotoname,
Toast.LENGTH_SHORT).show();
out.close();
} catch (Exception e) {
Log.e("Exception", e.toString());
}
}
});
Related
I have an ImageView in which I loaded a photo from server into it with Glide library.
I have a save button in which I want the image saved to gallery and internal storage when clicked after being loaded. I have tried several possibilities with no success as nothing seem to happen after I click the button.
public class ImagePreviewActivity extends AppCompatActivity {
ImageView imageView;
final File myDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/SmartPhoto");
boolean success = false;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_preview);
imageView = findViewById(R.id.image_preview);
saveImage();
}
private void saveImage() {
TextView mSave = findViewById(R.id.save_img);
mSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
final String fname = "image" + n + ".png";
myDir.mkdirs();
File image = new File(myDir, fname);
imageView.setDrawingCacheEnabled(true);
Bitmap bitmap = imageView.getDrawingCache();
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(),"Saved", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),"not saved", Toast.LENGTH_LONG).show();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
final Uri contentUri = Uri.fromFile(image);
scanIntent.setData(contentUri);
sendBroadcast(scanIntent);
} else {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://mnt/sdcard/" + Environment.getExternalStorageDirectory())));
}
}
});
}
}
Log Cat
02-24 14:40:41.288 1567-1575/? E/System: Uncaught exception thrown by finalizer
02-24 14:40:41.289 1567-1575/? E/System: java.lang.IllegalStateException: Binder has been finalized!
at android.os.BinderProxy.transactNative(Native Method)
at android.os.BinderProxy.transact(Binder.java:622)
at android.net.INetworkStatsSession$Stub$Proxy.close(INetworkStatsSession.java:476)
at android.app.usage.NetworkStats.close(NetworkStats.java:382)
at android.app.usage.NetworkStats.finalize(NetworkStats.java:118)
at java.lang.Daemons$FinalizerDaemon.doFinalize(Daemons.java:223)
at java.lang.Daemons$FinalizerDaemon.run(Daemons.java:210)
at java.lang.Thread.run(Thread.java:761)
AsyncTask, can be used to download Image .This proccess will be in background thread.
class DownloadImage extends AsyncTask<String,Integer,Long> {
String strFolderName;
#Override
protected void onPreExecute() {
super.onPreExecute();
}
#Override
protected Long doInBackground(String... aurl) {
int count;
try {
URL url = new URL((String) aurl[0]);
URLConnection conexion = url.openConnection();
conexion.connect();
String targetFileName="Name"+".rar";//Change name and subname
int lenghtOfFile = conexion.getContentLength();
String PATH = Environment.getExternalStorageDirectory()+ "/"+downloadFolder+"/";
File folder = new File(PATH);
if(!folder.exists()){
folder.mkdir();//If there is no folder it will be created.
}
InputStream input = new BufferedInputStream(url.openStream());
OutputStream output = new FileOutputStream(PATH+targetFileName);
byte data[] = new byte[1024];
long total = 0;
while ((count = input.read(data)) != -1) {
total += count;
output.write(data, 0, count);
}
output.flush();
output.close();
input.close();
} catch (Exception e) {}
return null;
}
protected void onPostExecute(String result) {
}
}
You can call this class like this new DownloadImage().execute(“yoururl”);
Don't forget to add these permissions in manifest file
<uses-permission android:name="android.permission.INTERNET"> </uses-permission>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"></uses-permission>
//out oncreate
final File myDir = new File(Environment.getExternalStorageDirectory().getAbsolutePath() + "/SmartPhoto");
boolean success = false;
//inside oncreate
mSave = (TextView) findViewById(R.id.save);
imageView = (ImageView) findViewById(R.id.header_cover_image);
mSave.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view)
{
saveImage();
}
});
public void saveImage()
{
final Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
final String fname = "image" + n + ".png";
myDir.mkdirs();
File image = new File(myDir, fname);
imageView.setDrawingCacheEnabled(true);
Bitmap bitmap = imageView.getDrawingCache();
// Encode the file as a PNG image.
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, outStream);
/* 100 to keep full quality of the image */
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(getApplicationContext(),"Saved", Toast.LENGTH_LONG).show();
} else {
Toast.makeText(getApplicationContext(),"not saved", Toast.LENGTH_LONG).show();
}
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
final Intent scanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
final Uri contentUri = Uri.fromFile(image);
scanIntent.setData(contentUri);
sendBroadcast(scanIntent);
} else {
sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://mnt/sdcard/" + Environment.getExternalStorageDirectory())));
}
}
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater=(LayoutInflater)cn.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View item_view= layoutInflater.inflate(R.layout.swipe_layout,container,false);
final ImageView imageView=(ImageView)item_view.findViewById(R.id.sl_imageView);
final TextView textView=(TextView)item_view.findViewById(R.id.tv_image);
Button save=(Button)item_view.findViewById(R.id.btn_save);
imageView.setImageResource(image_resource[position]);
textView.setText("Image :"+position);
final LinearLayout l_Layout=(LinearLayout)item_view.findViewById(R.id.LN_Layout);
final String imageNm=textView.getText().toString();
container.addView(l_Layout);
save.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
final Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
final String fname = imageNm+ ".jpg";
myDir.mkdirs();
File image = new File(myDir, fname);
Drawable drawable = cn.getResources().getDrawable(image_resource[position]);
Bitmap bitmap = ((BitmapDrawable) drawable).getBitmap();
FileOutputStream outStream;
try {
outStream = new FileOutputStream(image);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
/*100 to keep full quality of the image*/
outStream.flush();
outStream.close();
success = true;
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
if (success) {
Toast.makeText(cn,
"Image saved with success at /sdcard/temp_image",
Toast.LENGTH_LONG).show();
} else {
Toast.makeText(cn,
"Error during image saving", Toast.LENGTH_LONG)
.show();
}
cn.sendBroadcast(new Intent(Intent.ACTION_MEDIA_MOUNTED, Uri.parse("file://mnt/sdcard/" + Environment.getExternalStorageDirectory())));
}
});
I create take a screenshot in Android through a button click, but image can't be saved. I have an error message in "No such file or directory". What can I do?
My code:
public class MainActivity extends Activity {
LinearLayout L1;
ImageView image;
Bitmap bm;
File file;
FileOutputStream fileoutputstream;
View v1;
ByteArrayOutputStream bytearrayoutputstream;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
bytearrayoutputstream = new ByteArrayOutputStream();
L1 = (LinearLayout) findViewById(R.id.layout);
Button but = (Button) findViewById(R.id.Button01);
but.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
View v1 = L1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
image = (ImageView) findViewById(R.id.ImageView02);
image.setBackgroundDrawable(bitmapDrawable);
Log.e("top-->", String.valueOf(bitmapDrawable));
bm.compress(Bitmap.CompressFormat.PNG,60,bytearrayoutputstream);
//String path = Environment.getExternalStorageDirectory().toString();
File myDir = new File(Environment.getExternalStorageDirectory(), "saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try
{
FileOutputStream out = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
});
final ScrollView scrollview = (ScrollView) findViewById(R.id.scroll);
scrollview.getViewTreeObserver().addOnScrollChangedListener(new ViewTreeObserver.OnScrollChangedListener(){
#Override
public void onScrollChanged() {
if (scrollview != null) {
if (scrollview.getChildAt(0).getBottom() <= (scrollview.getHeight() + scrollview.getScrollY())) {
View v1 = L1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
image = (ImageView) findViewById(R.id.ImageView02);
image.setBackgroundDrawable(bitmapDrawable);
Log.e("top-->", String.valueOf(bitmapDrawable));
bm.compress(Bitmap.CompressFormat.PNG,60,bytearrayoutputstream);
//String path = Environment.getExternalStorageDirectory().toString();
File myDir = new File(Environment.getExternalStorageDirectory(), "saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try
{
FileOutputStream out = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
} else {
View v1 = L1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
image = (ImageView) findViewById(R.id.ImageView01);
image.setBackgroundDrawable(bitmapDrawable);
Log.e("bottom-->", String.valueOf(bitmapDrawable));
bm.compress(Bitmap.CompressFormat.PNG,60,bytearrayoutputstream);
// String path = Environment.getExternalStorageDirectory().toString();
File myDir = new File(Environment.getExternalStorageDirectory(), "saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try
{
FileOutputStream out = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
}
}
});
}
}
Image can't be saved in sdcard. What mistake did I make? I can't understand what is the problem or how to save an image on sdcard?
I use this method to capture screen. First, add proper permission to save file:
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
And this is the code (running in an Activity):
private void takeScreenshot() {
Date now = new Date();
android.text.format.DateFormat.format("yyyy-MM-dd_hh:mm:ss", now);
try {
// image naming and path to include sd card appending name you choose for file
String mPath = Environment.getExternalStorageDirectory().toString() + "/" + now + ".jpg";
// create bitmap screen capture
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
File imageFile = new File(mPath);
FileOutputStream outputStream = new FileOutputStream(imageFile);
int quality = 100;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, outputStream);
outputStream.flush();
outputStream.close();
openScreenshot(imageFile);
} catch (Throwable e) {
// Several error may come out with file handling or OOM
e.printStackTrace();
}
}
And this is how you can open the recently generated image:
private void openScreenshot(File imageFile) {
Intent intent = new Intent();
intent.setAction(Intent.ACTION_VIEW);
Uri uri = Uri.fromFile(imageFile);
intent.setDataAndType(uri, "image/*");
startActivity(intent);
}
Try this,
Before write the file you have to check the permissions for marshmallow
public static final int REQUEST_STORAGE = 101;
if (Build.VERSION.SDK_INT >= 23) {
String[] PERMISSIONS = {android.Manifest.permission.WRITE_EXTERNAL_STORAGE};
if (!hasPermissions(mContext, PERMISSIONS)) {
ActivityCompat.requestPermissions((Activity) mContext, PERMISSIONS, REQUEST_STORAGE);
} else {
writeFile()
}
}
/*check permissions for marshmallow*/
#SuppressWarnings("BooleanMethodIsAlwaysInverted")
private static boolean hasPermissions(Context context, String... permissions) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M && context != null && permissions != null) {
for (String permission : permissions) {
if (ActivityCompat.checkSelfPermission(context, permission) != PackageManager.PERMISSION_GRANTED) {
return false;
}
}
}
return true;
}
/*get Permissions Result*/
#Override
public void onRequestPermissionsResult(int requestCode, #NonNull String[] permissions, #NonNull int[] grantResults) {
super.onRequestPermissionsResult(requestCode, permissions, grantResults);
switch (requestCode) {
case REQUEST_STORAGE: {
if (grantResults.length > 0 && grantResults[0] == PackageManager.PERMISSION_GRANTED) {
Log.d("TAG", "PERMISSION_GRANTED");
writeFile();
} else {
Toast.makeText(mContext, "The app was not allowed to write to your storage", Toast.LENGTH_LONG).show();
}
}
}
}
public void writeFile()
{
View v1 = L1.getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bm = v1.getDrawingCache();
BitmapDrawable bitmapDrawable = new BitmapDrawable(bm);
image = (ImageView) findViewById(R.id.ImageView02);
image.setBackgroundDrawable(bitmapDrawable);
Log.e("top-->", String.valueOf(bitmapDrawable));
bm.compress(Bitmap.CompressFormat.PNG,60,bytearrayoutputstream);
//String path = Environment.getExternalStorageDirectory().toString();
File myDir = new File(Environment.getExternalStorageDirectory(), "saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 10000;
n = generator.nextInt(n);
String fname = "Image-"+ n +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try
{
FileOutputStream out = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
}
catch (Exception e)
{
e.printStackTrace();
}
}
final String root = Environment.getExternalStorageState().toString();
File myDir=new File(root + "/saved_images/" );
State is no storage. Change to:
File myDir = new File(Environment.getExternalStorageDirectory(), "saved_images" );
And adapt your code for mkdirs as explained in comment.
if (!myDir.exists())
{
if (!myDir.mkdirs())
{
Toast.makeText(this, "Sorry could not create directory:\n" + myDir.getAbsolutePath(), Toast.LENGTH_LONG).show();
return;
}
}
You complain that the file is not created but it starts with the directory.
You never answered my question about Androud version. But for 6.0 and above you should ask the user also for runtime permission. Add that code.
Or, as a quick solution, go to the Android settings of your app and switch the Storage toggle button to ON.
btnsave.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
mainLayout.setDrawingCacheEnabled(true);
// mainLayout.setDrawingCacheEnabled(true);
Bitmap bitmap =mainLayout.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/saved_images");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = "photo-" + n + ".jpg";
File file = new File(newDir, fotoname);
if (file.exists()) file.delete();
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
Toast.makeText(getApplicationContext(), "saved to your folder", Toast.LENGTH_SHORT).show();
} catch (Exception e) {
} }
});
btnshare.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
mainLayout.setDrawingCacheEnabled(true);
Bitmap bitmap =mainLayout.getDrawingCache();//Getting Complication error here.
// BitmapDrawable bitmapDrawable = (BitmapDrawable)ivdisplayphoto.getDrawable();
// Bitmap bitmap = bitmapDrawable.getBitmap();
//Using above code I am able to share one imageview.
// Save this bitmap to a file.
File cache = getApplicationContext().getExternalCacheDir();
File sharefile = new File(cache, "toshare.png");
try {
FileOutputStream out = new FileOutputStream(sharefile);
bitmap.compress(Bitmap.CompressFormat.PNG, 100, out);
out.flush();
out.close();
} catch (IOException e) {
}
// Now send it out to share
Intent share = new Intent(Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + sharefile));
try {
startActivity(Intent.createChooser(share, "Share photo"));
} catch (Exception e) {
}
}
});
}
I have 3 ImageViews As imageView1,imageView2,imageView3 and for layout
private RelativeLayout mainLayout;
mainLayout= (RelativeLayout) findViewById(R.id.childLayout);
Bitmap bitmap =mainLayout.getDrawingCache();
Only this was missing.
Now my code is working fine.
I have an image view in android and on that image view i have another image view.. Both image views contain two different images.. Now i want to save it as a single JPG image in my phone gallery.. So how can i do that??
I tried some code but it is not working.
Here is my code.
XML File:
<ImageView
android:id="#+id/innerImage"
android:layout_width="300dp"
android:layout_height="230dp"
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:contentDescription="#android:string/untitled"
android:background="#drawable/white"/>
<Button
android:id="#+id/btnselectPhoto"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="#+id/ivImage"
android:layout_alignLeft="#+id/ivImage"
android:layout_marginBottom="16dp"
android:text="#string/select_photo" />
<ImageView
android:id="#+id/ivImage"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:contentDescription="#android:string/untitled" />
<Button
android:id="#+id/btnsave"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="#id/btnselectPhoto"
android:layout_alignBottom="#id/btnselectPhoto"
android:layout_alignRight="#+id/ivImage"
android:layout_marginLeft="32dp"
android:layout_toRightOf="#id/btnselectPhoto"
android:text="#string/save" />
And here is my Java Code:
public class MainActivity extends ActionBarActivity {
private static String mTempDir;
Bitmap mBackImage, mTopImage, mBackground, mNewSaving;
Canvas mComboImage;
FileOutputStream mFileOutputStream;
BitmapDrawable mBitmapDrawable;
private String mCurrent = null;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Call method for selecting Image
SelectImage();
}
// method for selecting image
private void SelectImage() {
// items to put in alert box
final CharSequence[] items = { "Take Photo", "Choose from Library", "Cancel" };
// Alert box
final AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
builder.setTitle("Add Photo");
// Click Event of button
Button btn = (Button) findViewById(R.id.btnselectPhoto);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Set items in alert box
builder.setItems(items, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int item) {
// Start Camara
if (items[item].equals("Take Photo")) {
Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
File f = new File(android.os.Environment.getExternalStorageDirectory(), "temp.jpg");
intent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(f));
startActivityForResult(intent, 1);
}
// Open Gallery
else if (items[item].equals("Choose from Library")) {
Intent intent = new Itent(Intent.ACTION_PICK, android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
intent.setType("image/*");
startActivityForResult(intent, 2);
}
// Cancel code
else if (items[item].equals("Cancel")) {
dialog.dismiss();
}
}
});
builder.show();
}
});
}
// This method is called for setting image in imageview.
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
final String picturePath;
ImageView iv = (ImageView) findViewById(R.id.innerImage);
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 bm;
BitmapFactory.Options btmapOptions = new BitmapFactory.Options();
bm = BitmapFactory.decodeFile(f.getAbsolutePath(), btmapOptions);
// bm = Bitmap.createScaledBitmap(bm, 70, 70, true);
iv.setImageBitmap(bm);
String path = android.os.Environment.getExternalStorageDirectory() + File.separator + "Phoenix" + File.separator + "default";
f.delete();
OutputStream fOut = null;
File file = new File(path, String.valueOf(System.currentTimeMillis()) + ".jpg");
try {
fOut = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.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();
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = getContentResolver().query(selectedImage, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
picturePath = cursor.getString(columnIndex);
cursor.close();
// Bitmap thumbnail = (BitmapFactory.decodeFile(picturePath));
iv.setImageBitmap(BitmapFactory.decodeFile(picturePath));
saveimage(picturePath);
}
}
}
private void saveimage(String imgPath) {
mTempDir = Environment.getExternalStorageDirectory() + "/" + "Demo" + "/";
File mTempFile = new File(mTempDir);
if (!mTempFile.exists()) {
mTempFile.mkdirs();
}
mCurrent = "temp.png";
mBackground = Bitmap.createBitmap(604, 1024, Bitmap.Config.ARGB_8888);
mBackImage = BitmapFactory.decodeResource(getResources(), R.drawable.image1);
mTopImage = BitmapFactory.decodeFile(imgPath);
mComboImage = new Canvas(mBackground);
mComboImage.drawBitmap(mBackImage, 0f, 0f, null);
mComboImage.drawBitmap(mTopImage, 0f, 0f, null);
Button savebtn = (Button) findViewById(R.id.btnsave);
savebtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
try {
mBitmapDrawable = new BitmapDrawable(getResources(), 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) {
e.printStackTrace();
}
catch (IOException e) {
e.printStackTrace();
}
}
});
}
}
I worked on a similar issue once, and i solved it by putting both images in the same linear layout an creating Bitmap from that layout. Than you can just write a function to save that Bitmap where ever you want.
Here's some sample code:
private Bitmap getBitmap(View v) {
v.clearFocus();
v.setPressed(false);
boolean willNotCache = v.willNotCacheDrawing();
v.setWillNotCacheDrawing(false);
// Reset the drawing cache background color to fully transparent
// for the duration of this operation
int color = v.getDrawingCacheBackgroundColor();
v.setDrawingCacheBackgroundColor(0);
if (color != 0) {
v.destroyDrawingCache();
}
v.buildDrawingCache();
Bitmap cacheBitmap = v.getDrawingCache();
if (cacheBitmap == null) {
Toast.makeText(StopWarApp.getContext(), "Something went wrong",
Toast.LENGTH_SHORT).show();
return null;
}
Bitmap bitmap = Bitmap.createBitmap(cacheBitmap);
// Restore the view
v.destroyDrawingCache();
v.setWillNotCacheDrawing(willNotCache);
v.setDrawingCacheBackgroundColor(color);
return bitmap;
}
public void combineImages(Bitmap c, Bitmap s,String loc) {
Bitmap cs = null;
int width, height = 0;
if(c.getWidth() > s.getWidth()) {
width = c.getWidth();
height = c.getHeight() + s.getHeight();
} else {
width = s.getWidth();
height = c.getHeight() + s.getHeight();
}
cs = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
Canvas comboImage = new Canvas(cs);
comboImage.drawBitmap(c, 0f, 0f, null);
comboImage.drawBitmap(s, 0f, c.getHeight(), null);
String tmpImg = String.valueOf(System.currentTimeMillis()) + ".png";
OutputStream os = null;
try {
os = new FileOutputStream(loc + tmpImg);
cs.compress(CompressFormat.PNG, 100, os);
} catch(IOException e) {
Log.e("combineImages", "problem combining images", e);
}
}
You can combine two bitmaps using this.
LinearLayout ll;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.layout2);
ll=(LinearLayout)findViewById(R.id.linearlayout);
//Add button in your layout and write the below code onclick of button.
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
ll.setDrawingCacheEnabled(true);
Bitmap bitmap = ll.getDrawingCache();
String root = Environment.getExternalStorageDirectory().toString();
File newDir = new File(root + "/saved_picture");
newDir.mkdirs();
Random gen = new Random();
int n = 10000;
n = gen.nextInt(n);
String fotoname = n + ".jpg";
File file = new File(newDir, fotoname);
String s = file.getAbsolutePath();
System.err.print("Path of saved image." + s);
try {
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
}
}
});