Image isn't creating using the BitmapFactory.decodeByteArray - java

Edit:
When I save those bytes in the txt file and when I save it as png file , it shows the image, but it is not working here why...?
I am using this code to create image from byte array
on doInBackground()
String base64data=StringEscapeUtils.unescapeJava(IOUtils.toString(resp.getEntity().getContent()));
base64data=base64data.substring(1,base64data.length()-1);
JSONObject obj=new JSONObject(base64data);
JSONArray array=obj.getJSONArray("EMRTable");
JSONObject childobj=array.getJSONObject(0);
results=childobj.getString("DocumentInternalFormat");
and onPostExecute
if(jsondata!=null) {
receiveData(jsondata);
}
There is no error in the logcat, even there is no exception in it..but the image isn't showing. I have also did like this
String data=(String)object;
data=data.trim();
byte[] base64converted=Base64.decode(data,Base64.DEFAULT);
ImageView image=new ImageView(context);
image.setImageBitmap(bmp);
setContentView(image);
but the result same image isn't showing but there is no exception or an error, what is the problem...
The commented lines are when I try to store those bytes into text file and when I pull the file, it shows the images with windows default image viewer.

Try this code while getting bitmap from different resources...
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeByteArray(base64converted,0,base64converted.length,options);
// Calculate inSampleSize
options.inSampleSize = calculateInSampleSize(options, 500, 500);
// Decode bitmap with inSampleSize set
options.inJustDecodeBounds = false;
Bitmap bmp1=BitmapFactory.decodeByteArray(base64converted,0,base64converted.length,options);
follow the tutorial on this link Efficient way to show bitmaps

remove the below line from your code and try again
base64data=base64data.substring(1,base64data.length()-1);

Related

Image losing quality and size in android?

I have an app which takes photos of receipts and upload it to a remote server.
I get the full-sized photo of the image from the camera intent correctly.I followed this using the official documentation in Google developer.
I then set my picture like this.
private void setPic() {
// Get the dimensions of the View
int targetW = imageView.getWidth();
int targetH = imageView.getHeight();
// Get the dimensions of the bitmap
BitmapFactory.Options bmOptions = new BitmapFactory.Options();
bmOptions.inJustDecodeBounds = true;
BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
int photoW = bmOptions.outWidth;
int photoH = bmOptions.outHeight;
// Determine how much to scale down the image
int scaleFactor = Math.min(photoW/targetW, photoH/targetH);
// Decode the image file into a Bitmap sized to fill the View
bmOptions.inJustDecodeBounds = false;
bmOptions.inSampleSize = scaleFactor;
bmOptions.inPurgeable = true;
Bitmap bitmap = BitmapFactory.decodeFile(mCurrentPhotoPath, bmOptions);
//Bitmap bitmap = null;
//try
//{
//bitmap = MediaStore.Images.Media.getBitmap(getContentResolver() , //Uri.parse(mCurrentPhotoPath));
//}
//catch (Exception e)
//{
//handle exception
//}
imageView.setImageBitmap(bitmap);
new ImageSaver(getApplicationContext()).
setFileName("currentImage.png").
setDirectoryName("Android_Upload").
save(bitmap);
Model.currentImage = "currentImage.png";
}
This works fine when viewed on the device. But after its sent to the server and viewed from there, the image size is too small.
ImageSaver class pretty much saves the image elsewhere and compresses it but with 100 quality in png.I do this, so I can later the image in the database as Blob(again with 100 quality)
How can I decode the image and show the image in the image view but without losing quality (and the size?)
Apparently, you have scaled down your image while decoding.
You may want to remove the following line:
bmOptions.inSampleSize = scaleFactor;

Set ImageView from real path

I have the real path of an image which I am retrieving from my Database.
I want to set the ImageView by using the real path (/storage/emulated/0/DCIM/100MEDIA/image.jpg)
How can this be done?
public void getIMG(){
Cursor res = myDb.GetRow(id);
if(res.moveToFirst()){
String path = res.getString(DatabaseHelper.ROWIMG);
/*img.set'???'*/
}
}
hi try this and see if it helps you
String imagePath = cursor.getString(column_index_data);
File file = new File(imagePath);
file.getAbsolutePath();
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true ;
BitmapFactory.decodeFile(filePath , options);
options.inSampleSize = scaleFactor ;
options.inJustDecodeBounds = false ;
Bitmap newBitmap = BitmapFactory.decodeFile(filePath , options);
The best answer is to use a library like Picasso, to have it load the image in the background and apply it to your ImageView when the image is ready.
If you are determined to re-invent this wheel yourself, use BitmapFactory.decodeFile() on a background thread to read in the file and give you a Bitmap that you can pass to the ImageView.

Convert a File Object to Bitmap

I am using Universal-Image-Loader and there is this functionality that access the file cache of the image from sd card. But I don't know how to convert the returned file cache into bitmap. Basically I just wanted to assign the bitmap to an ImageView.
File mSaveBit = imageLoader.getDiscCache().get(easyPuzzle);
Log.d("#ImageValue: ", ""+mSaveBit.toString());
mImageView.setImageBitmap(mSaveBit);
Error: "The method setImageBitmap(Bitmap) in the type ImageView is not applicable for the arguments (File)"
You should be able to use BitmapFactory:
File mSaveBit; // Your image file
String filePath = mSaveBit.getPath();
Bitmap bitmap = BitmapFactory.decodeFile(filePath);
mImageView.setImageBitmap(bitmap);
Define File
String fileName = "/myImage.jpg";
File file = new File(fileName);
get Bitmap of Image
Bitmap bitmap = BitmapFactory.decodeFile(file.getAbsolutePath());
Set Bitmap to ImageView
myImageView.setImageBitmap(bitmap);
You can use this function to get Bitmap from file path
fun getBitmap(filePath:String):Bitmap?{
var bitmap:Bitmap?=null
try{
var f:File = File(path)
var options = BitmapFactory.Options()
options.inPreferredConfig = Bitmap.Config.ARGB_8888
bitmap = BitmapFactory.decodeStream(FileInputStream(f),null,options)
}catch (e:Exception){
}
return bitmap
}
Here is a simple code to create a scaled image for ImageView in this case
- Width:400
- Height:400
final File file = new File(Environment.getExternalStorageDirectory(),"b.jpg");
ImageView img = (ImageView) findViewById(R.id.imageview);
img.setImageBitmap(Bitmap.createScaledBitmap(BitmapFactory.decodeFile(file.getAbsolutePath()),400,400,false));
Kotlin Version
if (requestCode==PICK_IMAGE_REQUEST){
if (data!=null){
selectedfileUri=data.data
if (selectedfileUri!=null && !selectedfileUri!!.path.isEmpty()){
val file = FileUtils.getFile(context,selectedfileUri)
val bitmap = BitmapFactory.decodeFile(file.path)
uimg!!.setImageBitmap(bitmap)
}
}
}
This is not the right question, but if you use flag .cacheInMemory() in ImageLoader setup you can retrive the bitmap without need of recreate at any time using BitmapFactory to safe memory usage .
Just use:
Bitmap bitmap = ImageLoader.getInstance().getMemoryCache()·get("url as key");

Add image to PDF from a URL?

Im trying to add a image from a URL address to my pdf. The code is:
Image image=Image.getInstance("http://www.google.com/intl/en_ALL/images/logos/images_logo_lg.gif");
image.scaleToFit((float)200.0, (float)49.0);
paragraph.add(image);
But it does not work. What can be wrong?
This is a known issue when loading .gif from a remote location with iText.
A fix for this would be to download the .gif with Java (not via the getInstance method of iText's Image class) and to use the downloaded bytes in the getInstance method of the Image class.
Edit:
I went ahead and fixed remote gif loading in iText, it is included from iText 5.4.1 and later.
Adding Image into Itext PDF is not possible through URL .
Only way to add image in PDF is download all images in to local directory and apply below code
String photoPath = Environment.getExternalStorageDirectory() + "/abc.png";
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 8;
final Bitmap b = BitmapFactory.decodeFile(photoPath, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap.createScaledBitmap(b, 10, 10, false);
b.compress(Bitmap.CompressFormat.PNG, 30, stream);
Image img = null;
byte[] byteArray = stream.toByteArray();
try {
img = Image.getInstance(byteArray);
} catch (BadElementException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
The way you have used to add images to IText PDF is the way that is used for adding local files, not URLs.
For URLs, this way will solve the problem.
String imageUrl = "http://www.google.com/intl/en_ALL/"
+ "images/logos/images_logo_lg.gif";
Image image = Image.getInstance(new URL(imageUrl));
You may then proceed to add this image to some previously open document, using document.add(image).
For further reference, please visit the [Java IText: Image docs].

load data from sd return java.lang.nullpointerexception

The screen shot above show the path for my JPG file-/mnt/sdcard.
I try to load the image but it returnd java.lang.nullpointerexception. Below is my code.
String imagefile ="/mnt/sdcard/KFC_Voucher.JPG";
ImageView image = (ImageView)findViewById(R.id.image);
Bitmap bm = BitmapFactory.decodeFile(imagefile);
image.setImageBitmap(bm);
Please help.
R.id.image has to be in the layout you set trough setContentView(), else findViewById will return null

Categories

Resources