Saving an image to sd card from android pager - android

I have a pager activity in my android application I need to save the images according to there position in the pager. I managed to do the saving part but when iam in the first image i click save it saves the second image same for the second image it save the third i dont know whats wrong with my code! `
enter code here
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle item selection
if (item.getItemId()==R.id.menuFinale)
{
ImageView imageView = (ImageView) findViewById(R.id.image_one);
imageView.setDrawingCacheEnabled(true);
Bitmap bitmap = imageView.getDrawingCache();
File root = Environment.getExternalStorageDirectory();
MediaStore.Images.Media.insertImage(getContentResolver(), bitmap, "My pic" ,"Saved to gallery");
File file = new File(root.getAbsolutePath()+"/DCIM/Camera/img.jpg");
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.JPEG, 100, ostream);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return true;
}
else {
return super.onOptionsItemSelected(item);
}
}

Try some thing as below :
button=(Button)vi.findViewById(R.id.button_save);
button.setOnClickListener(new OnClickListener() {
private Bitmap bm;
private String PREFS_NAME;
public void onClick(View arg0) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root + "/saved_images");
if(!myDir.exists()){
myDir.mkdirs();}
bm = BitmapFactory.decodeResource( mContext.getResources(), images[itemPos]);
holder.image.setImageBitmap(bm);
SharedPreferences savedNumber = mContext.getSharedPreferences(PREFS_NAME, 0);
int lastSavedNumber = savedNumber.getInt("lastsavednumber",0);
lastSavedNumber++;
String fname = "Image-"+lastSavedNumber+".png";
File file = new File (myDir, fname);
if (file.exists ()) {file.delete (); }
try {
FileOutputStream out = new FileOutputStream(file);
bm.compress(Bitmap.CompressFormat.PNG, 100, out);//Your Bitmap from the resouce
out.flush();
out.close(); }
catch (Exception e) {
e.printStackTrace();
}
SharedPreferences saveNumber = mContext.getApplicationContext().getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor editorset = saveNumber.edit();
editorset.putInt("lastsavednumber",lastSavedNumber);
editorset.commit();
Toast.makeText(mContext, "saved", Toast.LENGTH_SHORT). show();}});
hope help you.

I managed finally to solve my issue instead of the imageView I'm referring to cache I must instead refer to ViewPager to cache all including the imageView instead here is my new code
enter code here
public boolean onOptionsItemSelected(MenuItem item)
{
// Handle item selection
if (item.getItemId()==R.id.menuFinale)
{
pager.setDrawingCacheEnabled(true);
pager.buildDrawingCache(true);
pager.setDrawingCacheEnabled(true);
Bitmap b = pager.getDrawingCache(true);
File root = Environment.getExternalStorageDirectory();
MediaStore.Images.Media.insertImage(getContentResolver(), b, "My pic" ,"Saved to gallery");
File file = new File(root.getAbsolutePath()+"/DCIM/HD.jpg");
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
b.compress(CompressFormat.JPEG, 100, ostream);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
return true;
}
else
{
return super.onOptionsItemSelected(item);
}
}

Related

Cannot save Bitmap image to Phone's Storage in Android

So, I am creating a QRCode generator application in which user can generate QR code from the data they have entered.I can successfully generate the QR code and show it to the imageview on a Button click but I am facing issue when I tried to save that QR code to my phone's storage (or gallery).
On this button click, QRGenerator function will be called and It will generate the QR code from the Edittext data.
btn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
QRGenerator();
}
});
Here is the QRGenerator() funcion :
private void QRGenerator() {
String data = text.getText().toString();
MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
try {
BitMatrix bitMatrix = multiFormatWriter.encode(data, BarcodeFormat.QR_CODE, 300, 300);
BarcodeEncoder barcodeEncoder = new BarcodeEncoder();
Bitmap bitmap = barcodeEncoder.createBitmap(bitMatrix);
imgView.setImageBitmap(bitmap);
bitmap2 = ((BitmapDrawable)imgView.getDrawable()).getBitmap();
saveImg.setVisibility(View.VISIBLE);
} catch (WriterException e) {
e.printStackTrace();
}
}
and from here I can call the save image function :
saveImg.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
saveImageFunction(bitmap2);
}
});
and here my issue arise, I have put a Toast to notify when my image will saved to gallery but it never pops up
Here is the saveImageFunction :
private void saveImageFunction(Bitmap bitmap) {
String savedImagePath = null;
String imageFileName = "JPEG_" + "test" + ".jpg";
File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+ "/Demo");
boolean success = true;
if(!storageDir.exists()){
success = storageDir.mkdirs();
}
if(success){
File imageFile = new File(storageDir, imageFileName);
savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
addToGallery(savedImagePath);
Toast.makeText(MainActivity.this,"Saved to Gallery!",Toast.LENGTH_SHORT).show();
}
}
and to put that saved image to gallery I have used this function :
addToGallery() :
private void addToGallery(String imagePath){
Intent mediaScanIntent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
File f = new File(imagePath);
Uri contentUri = Uri.fromFile(f);
mediaScanIntent.setData(contentUri);
sendBroadcast(mediaScanIntent);
}
As per Gk Mohammad Emon says, I tried adding Toast as well as Log.d in my catch method of SaveImage function but nothing pops up neither on Screen nor in LogCat (Please address any type of mistake if there) :
private void saveImageFunction(Bitmap bitmap) {
String savedImagePath = null;
String imageFileName = "JPEG_" + "test" + ".jpg";
File storageDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)+ "/Demo");
boolean success = true;
if(!storageDir.exists()){
success = storageDir.mkdirs();
}
if(success){
File imageFile = new File(storageDir, imageFileName);
savedImagePath = imageFile.getAbsolutePath();
try {
OutputStream fOut = new FileOutputStream(imageFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, fOut);
Toast.makeText(MainActivity.this,"Image Saved!", Toast.LENGTH_SHORT).show();
fOut.close();
} catch (Exception e) {
e.printStackTrace();
Toast.makeText(MainActivity.this,"hello There",Toast.LENGTH_SHORT).show();
Log.d("Exception e",e.toString());
}
addToGallery(savedImagePath);
Toast.makeText(MainActivity.this,"Saved to Gallery!",Toast.LENGTH_SHORT).show();
}
}

How to store background image from imageView in bitmap?

I am trying to store my image from imageView in bitmap, so that I can store it in the gallery of the android device. Every time I save an image, the background of the imageView is not stored. What am I missing?
Here is my code:
ImageView imageView = (ImageView) findViewById(R.id.img);
imageView.setBackgroundResource(R.drawable.img1);
BitmapDrawable draw = (BitmapDrawable) imageView.getDrawable();
Bitmap bitmap = draw.getBitmap();
Code to store the image into the gallery is:
FileOutputStream outStream = null;
File dir = new File(
Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
"MyAlbum");
if (!dir.exists()) {
if (!dir.mkdirs()) {
Log.d("MyAlbum", "failed to create directory");
Toast.makeText(MainActivity.this, "Failed to make directory", Toast.LENGTH_SHORT).show();
}
}
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
try {
outStream = new FileOutputStream(outFile);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, outStream);
outStream.flush();
outStream.close();
Toast.makeText(getApplicationContext(), "PICTURE SAVED", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
intent.setData(Uri.fromFile(dir));
sendBroadcast(intent);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
You can take a screenshot of this view (ImageView) in this case, it will simply take what's drawn on this view at this moment and turn it into a bitmap you can save.
Answer is mentioned here already.
The magical part is that
ImageView yourImageView = .. // Get reference it to your view.
yourImageView.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(yourImageView.getDrawingCache());
yourImageView.setDrawingCacheEnabled(false);
Ta-da you can use your snapshot btimap.
you can try this out,
private void saveImageToStorage(Bitmap finalBitmap, String image_name) {
String root = Environment.getExternalStorageDirectory().toString();
File myDir = new File(root);
myDir.mkdirs();
String fname = "Image-" + image_name+ ".jpg";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
Log.i("LOAD", root + fname);
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Happy coding :-)

I saved multiple image views as a single Image inside a layout.But using the same logic I am not able to do it for sharing button

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.

How to save a created bitmap?

I want to save a created bitmap after a button clicked
How can I do that? and if possible to a specific location
Here are my codes:
quoteimage.requestLayout();
if (quoteimage.getViewTreeObserver().isAlive()) {
quoteimage.getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
// we check which build version we are using
#SuppressLint("NewApi")
#SuppressWarnings("deprecation")
#Override
public void onGlobalLayout() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
quoteimage.getViewTreeObserver().removeGlobalOnLayoutListener(this);
} else {
quoteimage.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
viewToBitmap(quoteimage); ///this one creates the bitmap
}
});
}
share.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
///Here I want to save the bitmap
}
});
Call save() in onClick():
protected void save(){
FileOutputStream out = null;
try {
out = new FileOutputStream(filename);
bmp.compress(Bitmap.CompressFormat.PNG, 100, out); // bmp is your Bitmap instance
// PNG is a lossless format, the compression factor (100) is ignored
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (out != null) {
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}}
Use this method to save your bitmap, also pass the file name and location as U like
private createDirectoryAndSaveFile(Bitmap imageToSave, String fileName,String location) {
File direct = new File(Environment.getExternalStorageDirectory() + "/"+location);
if (!direct.exists()) {
File wallpaperDirectory = new File("/sdcard/"+location+"/");
wallpaperDirectory.mkdirs();
}
File file = new File(new File("/sdcard/"+location+"/"), fileName+".jpg");
if (file.exists()) {
file.delete();
}
try {
FileOutputStream out = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
File externalFile = new File(Environment.getExternalStorageDirectory(),"your/location/"+fileName+".jpg");
externaluri = Uri.parse(externalFile.getPath());
Log.d("externaluri", externaluri.toString());
}
Example
createDirectoryAndSaveFile(yourbitmap, "your_image_name" ,"your/location");
Android Saving created bitmap to directory on sd card
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
_bitmapScaled.compress(Bitmap.CompressFormat.JPEG, 40, bytes);
//you can create a new file name "test.jpg" in sdcard folder.
File f = new File(Environment.getExternalStorageDirectory()
+ File.separator + "test.jpg")
f.createNewFile();
//write the bytes in file
FileOutputStream fo = new FileOutputStream(f);
fo.write(bytes.toByteArray());
// remember close de FileOutput
fo.close();

How to save a bitmap on internal storage

this is my code I and I want to save this bitmap on my internal storage. The public boolean saveImageToInternalStorage is a code from google but I don't know how to use it. when I touch button2 follow the button1 action.
public class MainActivity extends Activity implements OnClickListener {
Button btn, btn1;
SurfaceView sv;
Bitmap bitmap;
Canvas canvas;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn=(Button)findViewById(R.id.button1);
btn1=(Button)findViewById(R.id.button2);
sv=(SurfaceView)findViewById(R.id.surfaceView1);
btn.setOnClickListener(this);
btn1.setOnClickListener(this);
bitmap=BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
}
#Override
public void onClick(View v) {
canvas=sv.getHolder().lockCanvas();
if(canvas==null) return;
canvas.drawBitmap(bitmap, 100, 100, null);
sv.getHolder().unlockCanvasAndPost(canvas);
}
public boolean saveImageToInternalStorage(Bitmap image) {
try {
// Use the compress method on the Bitmap object to write image to
// the OutputStream
FileOutputStream fos = openFileOutput("desiredFilename.png", Context.MODE_PRIVATE);
// Writing the bitmap to the output stream
image.compress(Bitmap.CompressFormat.PNG, 100, fos);
fos.close();
return true;
} catch (Exception e) {
Log.e("saveToInternalStorage()", e.getMessage());
return false;
}
}
}
To Save your bitmap in sdcard use the following code
Store Image
private void storeImage(Bitmap image) {
File pictureFile = getOutputMediaFile();
if (pictureFile == null) {
Log.d(TAG,
"Error creating media file, check storage permissions: ");// e.getMessage());
return;
}
try {
FileOutputStream fos = new FileOutputStream(pictureFile);
image.compress(Bitmap.CompressFormat.PNG, 90, fos);
fos.close();
} catch (FileNotFoundException e) {
Log.d(TAG, "File not found: " + e.getMessage());
} catch (IOException e) {
Log.d(TAG, "Error accessing file: " + e.getMessage());
}
}
To Get the Path for Image Storage
/** Create a File for saving an image or video */
private File getOutputMediaFile(){
// To be safe, you should check that the SDCard is mounted
// using Environment.getExternalStorageState() before doing this.
File mediaStorageDir = new File(Environment.getExternalStorageDirectory()
+ "/Android/data/"
+ getApplicationContext().getPackageName()
+ "/Files");
// This location works best if you want the created images to be shared
// between applications and persist after your app has been uninstalled.
// Create the storage directory if it does not exist
if (! mediaStorageDir.exists()){
if (! mediaStorageDir.mkdirs()){
return null;
}
}
// Create a media file name
String timeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
File mediaFile;
String mImageName="MI_"+ timeStamp +".jpg";
mediaFile = new File(mediaStorageDir.getPath() + File.separator + mImageName);
return mediaFile;
}
EDIT
From Your comments i have edited the onclick view in this the button1 and button2 functions will be executed separately.
public onClick(View v){
switch(v.getId()){
case R.id.button1:
//Your button 1 function
break;
case R.id. button2:
//Your button 2 function
break;
}
}
private static void SaveImage(Bitmap finalBitmap) {
String root = Environment.getExternalStorageDirectory().getAbsolutePath();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
String fname = "Image-"+ o +".jpg";
File file = new File (myDir, fname);
if (file.exists ()) file.delete ();
try {
FileOutputStream out = new FileOutputStream(file);
finalBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Modify onClick() as follows:
#Override
public void onClick(View v) {
if(v == btn) {
canvas=sv.getHolder().lockCanvas();
if(canvas!=null) {
canvas.drawBitmap(bitmap, 100, 100, null);
sv.getHolder().unlockCanvasAndPost(canvas);
}
} else if(v == btn1) {
saveBitmapToInternalStorage(bitmap);
}
}
There are several ways to enforce that btn must be pressed before btn1 so that the bitmap is painted before you attempt to save it.
I suggest that you initially disable btn1, and that you enable it when btn is clicked, like this:
if(v == btn) {
...
btn1.setEnabled(true);
}
To save file into directory
public static Uri saveImageToInternalStorage(Context mContext, Bitmap bitmap){
String mTimeStamp = new SimpleDateFormat("ddMMyyyy_HHmm").format(new Date());
String mImageName = "snap_"+mTimeStamp+".jpg";
ContextWrapper wrapper = new ContextWrapper(mContext);
File file = wrapper.getDir("Images",MODE_PRIVATE);
file = new File(file, "snap_"+ mImageName+".jpg");
try{
OutputStream stream = null;
stream = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG,100,stream);
stream.flush();
stream.close();
}catch (IOException e)
{
e.printStackTrace();
}
Uri mImageUri = Uri.parse(file.getAbsolutePath());
return mImageUri;
}
required permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
You might be able to use the following for decoding, compressing and saving an image:
#Override
public void onClick(View view) {
onItemSelected1();
InputStream image_stream = null;
try {
image_stream = getContentResolver().openInputStream(myUri);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
Bitmap image= BitmapFactory.decodeStream(image_stream );
// path to sd card
File path=Environment.getExternalStorageDirectory();
//create a file
File dir=new File(path+"/ComDec/");
dir.mkdirs();
Date date=new Date();
File file=new File(dir,date+".jpg");
OutputStream out=null;
try{
out=new FileOutputStream(file);
image.compress(format,size,out);
out.flush();
out.close();
MediaStore.Images.Media.insertImage(getContentResolver(), image," yourTitle "," yourDescription");
image=null;
}
catch (IOException e)
{
e.printStackTrace();
}
Toast.makeText(SecondActivity.this,"Image Save Successfully",Toast.LENGTH_LONG).show();
}
});

Categories

Resources