How to Save image into local storage loaded with Glide? - android

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())));
}
}

Related

how to save image and textview text in gallery from viewPager. It save only image

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())));
}
});

android : share gif image from drawable

I want to share .gif from my app to facebook,gmail.
hello there is any way to share gif image
i have gif in drawable folder ("giphy.gif")
below are code that i have try , but it give me error.(no attached file)
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
shareGif("giphy");
}
private void shareGif(String resourceName) {
String baseDir = Environment.getExternalStorageDirectory().getAbsolutePath();
String fileName = "giphy.gif";
File sharingGifFile = new File(baseDir, fileName);
try {
byte[] readData = new byte[1024 * 500];
InputStream fis = getResources().openRawResource(getResources().getIdentifier(resourceName, "drawable", getPackageName()));
FileOutputStream fos = new FileOutputStream(sharingGifFile);
int i = fis.read(readData);
while (i != -1) {
fos.write(readData, 0, i);
i = fis.read(readData);
}
fos.close();
} catch (IOException io) {
}
Intent shareIntent = new Intent(android.content.Intent.ACTION_SEND);
shareIntent.setType("image/gif");
Uri uri = Uri.fromFile(sharingGifFile);
shareIntent.putExtra(Intent.EXTRA_STREAM, uri);
startActivity(Intent.createChooser(shareIntent, "Share Emoji"));
}
}
First add permission
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>
Then you have to save the gif to external storage, and finally load that file.
try {
CopyRAWtoSDCard(mContext,R.drawable.giphy, "giphy");
} catch (IOException e) {
e.printStackTrace();
}
File sdcard = Environment.getExternalStorageDirectory();
File file = new File(sdcard,"/yourapp/giphy.gif");
it.setType("image/*");
it.putExtra(Intent.EXTRA_STREAM, Uri.fromFile(file));
it.putExtra(Intent.EXTRA_SUBJECT, mContext.getString(R.string.app_name));
it.putExtra(Intent.EXTRA_TEXT, "Gif attached");
it.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
Intent in = Intent.createChooser(it,"Share");
in.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
mContext.startActivity(in);
private void CopyRAWtoSDCard(Context mContext,int id,String name) throws IOException {
String path = Environment.getExternalStorageDirectory() + "/yourapp";
File dir = new File(path);
if (dir.mkdirs() || dir.isDirectory()) {
try {
InputStream in = mContext.getResources().openRawResource(id);
FileOutputStream out = new FileOutputStream(path+ File.separator + name+".gif");
byte[] buff = new byte[1024];
int read = 0;
try {
while ((read = in.read(buff)) > 0) {
out.write(buff, 0, read);
}
} finally {
in.close();
out.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
Works like a Charm!

java.io.FileNotFoundException: mounted/saved_images/Image-6999.jpg (No such file or directory)

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.

save camera image into directory

I am working on a application in which I have to click the image from the camera and save it into directory.I am able to create directory named MyPersonalFolder and also images are going into it but when I am trying to open that image to see, it doesn't open and shows the message that that image cannot be opened. here is my code. Can anyone please tell me what mistake I am doing here.
I have also mentioned permissions in manifest .
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
<uses-feature android:name="android.hardware.camera" />
public class Camera extends Activity{
private static final String TAG = "Camera";
private static final int CAMERA_PIC_REQUEST = 1111;
Button click , share;
ImageView image;
String to_send;
String filename;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.camera);
image = (ImageView)findViewById(R.id.image);
share = (Button)findViewById(R.id.share);
click = (Button)findViewById(R.id.click);
click.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE);
startActivityForResult(intent, CAMERA_PIC_REQUEST);
}
});
share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
BitmapDrawable bitmapDrawable = (BitmapDrawable)image.getDrawable();
Bitmap bitmap = bitmapDrawable.getBitmap();
// 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(android.content.Intent.ACTION_SEND);
share.setType("image/*");
share.putExtra(Intent.EXTRA_STREAM, Uri.parse("file://" + sharefile.getAbsolutePath()));
try {
startActivity(Intent.createChooser(share, "Share photo"));
} catch (Exception e) {
}
/*Intent share = new Intent(Intent.ACTION_SEND);
share.setType("text/plain");
//String to_send = null;
share.putExtra(Intent.EXTRA_TEXT, to_send);
startActivity(Intent.createChooser(share, "Share using..."));*/
}
});
}
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
FileOutputStream outStream = null;
if (requestCode == CAMERA_PIC_REQUEST) {
//2
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
image.setImageBitmap(thumbnail);
//3
share.setVisibility(0);
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
//4
try {
File sdCard = Environment.getExternalStorageDirectory();
File dir = new File (sdCard.getAbsolutePath() + "/MyPersonalFolder");
dir.mkdirs();
String fileName = String.format("%d.jpg", System.currentTimeMillis());
File outFile = new File(dir, fileName);
outStream = new FileOutputStream(outFile);
//outStream.write(data[0]);
outStream.flush();
outStream.close();
//Log.d(TAG, "onPictureTaken - wrote bytes: " + data.length + " to " + outFile.getAbsolutePath());
refreshGallery(outFile);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
/*try {
file.createNewFile();
FileOutputStream fo = new FileOutputStream(file);
//5
fo.write(bytes.toByteArray());
fo.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();*/
}
}
}
private void refreshGallery(File file) {
Intent mediaScanIntent = new Intent( Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
mediaScanIntent.setData(Uri.fromFile(file));
sendBroadcast(mediaScanIntent);
}
}
You will need to use MediaScanner to notify the system of the new file/directory. You can try something like this after creating and saving the new file:
/**
* Adds the new photo/video to the device gallery, else it will remain only visible via sd card
*
* #param path
*/
public static void addToGallery(Context context, String path) {
MediaScanner scanner = new MediaScanner(path, null);
MediaScannerConnection connection = new MediaScannerConnection(context, scanner);
scanner.connection = connection;
connection.connect();
}
/**
* Scans the sd card for new videos/images and adds them to the gallery
*/
private static final class MediaScanner implements MediaScannerConnection.MediaScannerConnectionClient {
private final String path;
private final String mimeType;
MediaScannerConnection connection;
public MediaScanner(String path, String mimeType) {
this.path = path;
this.mimeType = mimeType;
}
#Override
public void onMediaScannerConnected() {
connection.scanFile(path, mimeType);
}
#Override
public void onScanCompleted(String path, Uri uri) {
connection.disconnect();
}
}
EDIT:
You are also forgetting to write the byte array to the file specified in the output stream, like in the code that you have commented out. Try this at the end just before you refresh the gallery:
outStream = new FileOutputStream(outFile);
outStream.write(bytes.toByteArray()); //this is the line you had missing
outStream.flush();
outStream.close();
Also take note that using Intent.ACTION_MEDIA_SCANNER_SCAN_FILE to refresh the gallery can also present you with some security issues on kitkat (cant remember exactly what the issues were). So just make sure you test it on kitkat device to confirm that it works correctly

How to save images from imageView to SD

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());
}
}
});

Categories

Resources