I have a simple question. How can I save Picasso image (that loads successfully from json) into database. I want to convert it into a bitmap if it possible, or is there another way to save it?
I tried this method for drawable images and its work perfectly.
My code:
public static byte[] imageViewToByte(ImageView image) {
Bitmap bitmap = ((BitmapDrawable) image.getDrawable()).getBitmap();
// Bitmap bitmap=(BitmapDrawable)image.getI);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
return byteArray;`.
}
After successful load of image set to picasso then , use below code to convert image url to bitmap :
try {
URL url = new URL("http://....");
Bitmap image = BitmapFactory.decodeStream(url.openConnection().getInputStream());
} catch(IOException e) {
System.out.println(e);
}
or, use below :
public static Bitmap getBitmapFromURL(String src) {
try {
URL url = new URL(src);
HttpURLConnection connection = (HttpURLConnection) url.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
Bitmap myBitmap = BitmapFactory.decodeStream(input);
return myBitmap;
} catch (IOException e) {
e.printStackTrace();
return null;
}
}
By using sharedpreference ,you can save bitmap to internal storage .
Related
here is the code which I tried.
I'm not getting the image in bmp using Glide and when I pass the null bmp in the method which converts the image to the byte[] then the error occurs.
new AsyncTask() {
#Override
protected byte[] doInBackground(Void... voids) {
Looper.prepare();
byte[] byteimage = new byte[0];
Bitmap bmp1;
try {
bmp= Glide.with(specificrecipe.this)//bmp is global
.load(url2img)
.asBitmap()
.into(100,100)
.get();
byteimage=getBytes(bmp);//here I'm not getting the image in bmp
//ByteArrayOutputStream stream = new ByteArrayOutputStream();
//bmp.compress(Bitmap.CompressFormat.PNG, 0, stream);//null object refrence -> bmp
//byteimage=stream.toByteArray();
//byteimage1.add(0,byteimage);
// initialize(bmp);
}catch (final ExecutionException e){e.printStackTrace();}
catch (final InterruptedException e){e.printStackTrace();}
return byteimage;
}
//#Override
//protected void onPostExecute(byte[] Bytearray){
//byteimage1=Bytearray;
//}
}.execute();
Hope this works for you
Bitmap theBitmap = Glide.
with(this).
load("http://....").
asBitmap().
into(100, 100). // Width and height
get();
//this is the way through which I get the image from URL even the glide is not working for saving the image from URL.
try {
URL url = new URL(url2img);//url2img is a String
bmp =BitmapFactory.decodeStream(url.openConnection().getInputStream());
//bmp is global variable
}catch (IOException e)
{e.printStackTrace();}
byteimage1=getBytes(bmp);
When I take an image by Camera, its works fine and I get the image path to save in SQLite database and can retrieve the path to show required image. But when I select an image from Gallery I don't get the correct path which I need to save in database for the further retrieve. I don't get image cause the path is incorrect when I save path in the database. So my question is - how can I get the correct absolute path of the gallery image?
#RequiresApi(api = Build.VERSION_CODES.N)
private void onCaptureImageResult(Intent data) {
Bitmap thumbnail = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
thumbnail.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeFile(destination.getAbsolutePath());
ivImage.setImageBitmap(bm);
showImagepathET.setText(destination.getAbsolutePath());// This path will save in database
}
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
showImagepathET.setText(destination.getAbsolutePath());// This path will save in database
ivImage.setImageBitmap(bm);
}
Here, I get the correct image to show in ImageView ivImage in both take an image by camera or gallery. But I don't get the path correctly when I pick an image from Gallery(works fine when I take camera Image) which I save in database for further path retrieve.
how i can get this selected image path
For what feels like the 3,735th time, there is no "selected image path". You are getting a Uri back (data.getData()); a Uri does not have to point to a file. For example, http://stackoverflow.com/questions/44057912/not-getting-correct-path-when-select-image-from-gallery is a Uri; it does not represent a file on the filesystem.
If you want a file, use a file-picker library.
At last, I decided to do the same procedure what I did in Method "onCaptureImageResult(Intent data)". The image I get from the Gallery stored again to a directory.I know this is absolutely not the good procedure, but it solved my problem temporally until I get a good answer.
#SuppressWarnings("deprecation")
private void onSelectFromGalleryResult(Intent data) {
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 90, bytes);
File destination = new File(Environment.getExternalStorageDirectory(), System.currentTimeMillis() + ".jpg");
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Bitmap bm1 = BitmapFactory.decodeFile(destination.getAbsolutePath());
ivImage.setImageBitmap(bm1);
String selectedImageUri = data.getData().getPath();
showImagepathET.setText(destination.getAbsolutePath());
}
I was having some problem when trying to attach a generated QR code as attachment using email in Android Programming. Here is the part where I generate the QR code and then call the send email:
#SuppressLint("NewApi")
private void generateQR() {
// Find screen size
WindowManager manager = (WindowManager) getSystemService(WINDOW_SERVICE);
Display display = manager.getDefaultDisplay();
Point point = new Point();
display.getSize(point);
int width = point.x;
int height = point.y;
// Encode with a QR Code image
QRCodeEncoder qrCodeEncoder = new QRCodeEncoder(qrInputText, null,
Contents.Type.TEXT, BarcodeFormat.QR_CODE.toString(),
smallerDimension);
try {
Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
ImageView myImage = (ImageView) findViewById(R.id.ivImage);
myImage.setImageBitmap(bitmap);
new SendEmailAsyncTask().execute(bitmap);
} catch (WriterException e) {
e.printStackTrace();
}
}
class SendEmailAsyncTask extends AsyncTask <Bitmap, Void, Boolean> {
#Override
protected Boolean doInBackground(Bitmap... params) {
GMailSender sender = new GMailSender("something#gmail.com","pwd");
try {
sender.sendMail("Successful Event Registration QR Code",params[0], "something#gmail.com", "something#gmail.com");
System.out.println("send");
} catch (Exception e) {
System.err.println("err"+e);
Log.e("SendMail", e.getMessage(), e);
}
return null;
}
}
However, I am getting error message at the sendMail that line:
The method sendMail(String, String, String, String) in the type GMailSender is not applicable for the arguments (String, Bitmap, String, String)
Because previously when I replace the params[0], it was a string before that. But then I have to pass in the generated QR code bitmap into the email content. Any ideas?
Thanks in advance.
Update
Bitmap bitmap = qrCodeEncoder.encodeAsBitmap();
ImageView myImage = (ImageView) findViewById(R.id.ivImage);
myImage.setImageBitmap(bitmap);
counterQR++;
String path = Environment.getExternalStorageDirectory().toString();
OutputStream fOut = null;
File file = new File(path, "eNeighbourhood"+counterQR+".jpg");
fOut = new FileOutputStream(file);
Bitmap pictureBitmap = getImageBitmap(bitmap); // obtaining the Bitmap
pictureBitmap.compress(Bitmap.CompressFormat.JPEG, 85, fOut);
fOut.flush();
fOut.close();
MediaStore.Images.Media.insertImage(getContentResolver(),file.getAbsolutePath(),file.getName(),file.getName());
With these code above, I am trying to convert bitmap into file so that I can modify the sendMail() by taking in file parameter as well. However, I am getting getImageBitmap is undefined for MainActivity
I wonder how to display image if I have a Bitmap and don't want to give as a parameter URL to image using Universal ImageLoader library.
Bitmap img = getDefaultBitmap();
ImageLoader.getInstance().displayImage(img); // I need something like this (for example with parameters to display image like width and height)
Firstly,
you have to save bitmap and then u can pass that path to show that bitmap into imageview using imageloader.
//-- Saving file
String filename = "pippo.jpg";
File sd = Environment.getExternalStorageDirectory();
File dest = new File(sd, filename);
Bitmap bitmap = (Bitmap)data.getExtras().get("data");
try {
FileOutputStream out = new FileOutputStream(dest);
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
//-- show bitmap to imageview
imageLoader.displayImage(dest.getAbsolutePath(), imageView);
I'm trying to create an app which allows users to screenshot the current view. I'm using the following code to do so.
View content = ((Activity)ctx).findViewById(R.id.rootlayout);
Bitmap bitmap = content.getDrawingCache();
File file = new File("/sdcard/test.png");
try
{
file.createNewFile();
FileOutputStream ostream = new FileOutputStream(file);
bitmap.compress(CompressFormat.PNG, 100, ostream);
ostream.close();
}
catch (Exception e)
{
e.printStackTrace();
}
However, i'm getting a Null Pointer Exception on the following line:
Bitmap bitmap = content.getDrawingCache();
What would this mean, that the view is empty?
Any help would be great!
You need to call content.setDrawingCacheEnabled(true); before you can use that. Then call content.setDrawingCacheEnabled(false); when you're done.