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();
}
}
Related
I'm trying to save a RelativeLayout as a bitmap and insert it into the gallery, the code below throws this exception:
java.lang.NullPointerException
at java.io.File.<init>(File.java:282)
at maa.Fragements.ColorPaletteFragment.galleryAddPic(ColorPaletteFragment.java:344)
because the parameter imagePath of galleryAddPic method is empty or null
insert Image to gallery:
private void galleryAddPic(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);
getActivity().sendBroadcast(mediaScanIntent);
}
saving the image:
#SuppressLint("StaticFieldLeak")
public class saveViewAsBitmap extends AsyncTask<RelativeLayout, String, String> {
#SuppressLint("SetTextI18n")
#Override
protected void onPreExecute() {
super.onPreExecute();
txt.setText("Saving image to gallery ...");
}
#Override
protected String doInBackground(RelativeLayout... relatives) {
String savedImagePath = null;
String imageFileName = "inColor" + System.currentTimeMillis() + ".png";
Bitmap image = getBitmapFromView(relatives[0]);
File storageDir = new File(
Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES)
+ "/inColor Folder");
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);
image.compress(Bitmap.CompressFormat.PNG, 100, fOut);
fOut.close();
} catch (Exception e) {
e.printStackTrace();
}
dialogLoading.dismiss();
}
return savedImagePath;
}
#Override
protected void onPostExecute(String path) {
super.onPostExecute(path);
galleryAddPic(path);
}
}
can anyone help me to get resolve this issue?
Make sure that you have
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
in Manifest file
I face a problem when downloading an image from remote server. The image is initially transparent but when I download it the transparency changes into a black background.
Callable.invoke(new Callable<Response>() {
#Override
public Response call() throws Exception {
return service.getImage(image);
}
}, new TaskCallback<Response>() {
#Override
public void success(final Response result) {
try {
InputStream in = result.getBody().in();
Bitmap b = BitmapFactory.decodeStream(in);
String mDirectoryPathname = Environment
.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES)+ "/images/";
String timestamp = new SimpleDateFormat("yyyyMMdd'_'HHmmssSSS")
.format(new Date());
String filename = timestamp + ".png";
final Uri uri = ImageDownloadUtils.createDirectoryAndSaveFile(
context,
b,
filename,
mDirectoryPathname);
} catch (IOException e) {
e.printStackTrace();
}
}
#Override
public void error(Exception e) {
Log.e(TAG, "Error getting image via OAuth.", e);
}
});
Here is the factory method which is called to save the image.
public static Uri createDirectoryAndSaveFile(Context context,
Bitmap imageToSave,
String fileName,
String directoryPathname) {
if (imageToSave == null)
return null;
File directory = new File(directoryPathname);
if (!directory.exists()) {
directory.mkdirs();
}
File file = new File(directory, getTemporaryFilename(fileName));
if (file.exists())
file.delete();
try {
FileOutputStream outputStream = new FileOutputStream(file);
imageToSave.compress(Bitmap.CompressFormat.JPEG,
100,
outputStream);
outputStream.flush();
} catch (Exception e) {
return null;
}
String absolutePathToImage = file.getAbsolutePath();
ContentValues values = new ContentValues();
values.put(MediaStore.Images.Media.TITLE, fileName);
values.put(MediaStore.Images.Media.DESCRIPTION, fileName);
values.put(MediaStore.Images.Media.DATE_TAKEN, System.currentTimeMillis());
values.put(MediaStore.Images.ImageColumns.BUCKET_DISPLAY_NAME,
file.getName().toLowerCase(Locale.US));
values.put("_data",
absolutePathToImage);
ContentResolver cr = context.getContentResolver();
cr.insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
return Uri.parse(absolutePathToImage);
}
This is not the problem with image's transparency. When you download an image and view it in Gallery, it is showing the image in an ImageView. That ImageView has a default background of black colour. That's why the transparent part of the downloaded image appears as black.
If you are showing the image in your application, set the background of ImageView to transparent.
android:background="#android:color/transparent"
in XML or
imageView.setBackgroundColor(Color.TRANSPARENT);
through code.
EDIT: If still the problem persists, try this :
InputStream in = result.getBody().in();
Bitmap b = BitmapFactory.decodeStream(in);
String mDirectoryPathname = Environment
.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES) + "/images/";
String timestamp = new SimpleDateFormat("yyyyMMdd'_'HHmmssSSS").format(new Date());
String filename = timestamp + ".png";
try {
File file = new File(mDirectoryPathname, filename);
FileOutputStream outputStream = new FileOutputStream(file);
b.compress(Bitmap.CompressFormat.PNG, 100, outputStream);
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
final Uri uri = Uri.fromFile(file);
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 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);
}
}
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();
}
});