Convert Byte to Bitmap - java

I have to convert a byte to Bitmap and i set it to imageview
i do have methode that convert Bitmap in ImageView into Byte and i insert it later,
public static byte[] ConvertDrawableToByteArray(Drawable drawableResource) {
Bitmap imageBitmap = ((BitmapDrawable) drawableResource).getBitmap();
ByteArrayOutputStream imageByteStream = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, imageByteStream);
byte[] imageByteData = imageByteStream.toByteArray();
return imageByteData;
}
and when i want to retrieve image from database and show it in an ImageView i do
//--
byte[] image_b = c.getBlob(4);
Bitmap b = BitmapFactory.decodeByteArray(image_b, 0, image_b.length);
img.setImageBitmap(b);
but it return nothing
what is wrong, please help
Thanks a lot

I guess it's because the cursor didn't return anything. Maybe the Blob is too big to be queried in one time because android cursor limit is 1 mb per query please check again your stacktrace/logcat and if the blob size is the problem you can try to split the byte to smaller size and store it in your database

You can play around with the following and let us know if it works:
String[] filePathColumn = { MediaStore.Images.Media.DATA };
Cursor cursor = resolver.query(imageUri, filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
return BitmapFactory.decodeFile(picturePath);

I dont understand where is the problèlme i do likee this :String t = image_b.toString(); System.out.println("what it give me" +t); and i find in the logcat this line : 03-19 17:01:28.167: I/System.out(1019): what it give me[B#41f1f5c0
is that mean it return something but dont showin or is the byte [B#41f1f5c0 is not correct

Related

Android Studio (java): Image from array to PDF using iText

Currently the user selects their images within a fragment and it converts them into an array with a string path name. I want to put that image on the PDF, but there is a formatting issue. I am trying to use the code below to fix that. Currently everything checks through until the cursor.MoveToFirst() returns null.
for (int i = 0; i <= imgArray.size(); i++) {
Uri selectedImageUri = Uri.fromFile(new File(imgArray.get(i)));
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImageUri, filePathColumn, null, null, null);
cursor.moveToFirst(); //ERROR: NULL
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bmp = BitmapFactory.decodeFile(picturePath);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
doc.add(image);
}
SOLUTION: I figured this out. This seems to work for me! Use bitmap configurations.
for (int i = 0; i < imgArray.size(); i++) {
Bitmap bmp = BitmapFactory.decodeFile(imgArray.get(i));
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
doc.add(image);
}

Image uploading from android to PHP server using retrofit

I am uploading image to server using retrofit. I am encoding image to bitmap and then convert bitmap to string and passing string to PHP. On PHP side I decode image again and then save to server folder.
It works perfectly if I compress image quality to 30 but app crashes and shows null pointer if I set image quality to 100.
Here is my Code:
ResultActivity:
if (requestCode == 1 && null != data) {
Uri selectedImage = data.getData();
String[] filePathColumn = {MediaStore.Images.Media.DATA};
Cursor cursor = getContentResolver().query(selectedImage,
filePathColumn, null, null, null);
cursor.moveToFirst();
int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
String picturePath = cursor.getString(columnIndex);
// photo = BitmapFactory.decodeFile(picturePath);
profile_photo =
ImageUtils.getInstant().getCompressedBitmap(picturePath);
Uri tempUri = getImageUri(this, profile_photo);
cursor.close();
profile_image.setImageResource(android.R.color.transparent);
Picasso.get()
.load(tempUri)
.resize(150, 150)
.into(profile_image);
profile_image.setScaleType(ImageView.ScaleType.FIT_XY);
profile_image.setPadding(5, 5, 5, 5);
//Bitmap profile_photo = ((BitmapDrawable)
profile_image.getDrawable()).getBitmap();
upload_profileimage();
b.dismiss();
}
Bitmap to string:
public String BitmapTOString(Bitmap bitmap) {
Bitmap bm = bitmap;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] byteFormat = stream.toByteArray();
String imgString = Base64.encodeToString(byteFormat, Base64.DEFAULT);
return imgString;
}
Retrofit API call:
call = user_profileimge_interface.profileImage_uplaod(BitmapTOString(profile_photo), user_id);
PHP Code:
$data = $baseurl.'user_profile_pictures/'.$user_id.".JPEG";
file_put_contents($data, base64_decode($profile_picture));
echo json_encode(Array('message' => "image inserted"));
API interface:
#POST("update_profilepic.php")
Call<Profile_Image_updateJson> profileImage_uplaod(#Query("profile_picture") String profileImage,
#Query("user_id") String user_id);
I'd suggest sending bitmap as binary data rather than converting to/from string. For example:
#POST
Call<Profile_Image_updateJson> profileImage_uplaod(#Query("user_id") String user_id, #Body RequestBody body);
and then something like:
requestBody = RequestBody.create(MediaType.parse("image/jpeg"), imageBytes)
call = user_profileimge_interface.profileImage_uplaod(user_id, requestBody);
Try to Perform BitmaptoString() operation in a separate thread, away from the Main UI Thread.
As processing bitmap is too costly if you perform it in the Main UI Thread, the App might crash. Also, you can use Asynctask or Any Background Process to perform costly functions and avoid any costly operations in Main Thread.

Cannot resolve symbol length

I want to retrieve a list of images from SQLite.
This is my 'getImage()' method
public List<byte[]> getImage(int i) {
List<byte[]> list = new ArrayList<>();
String selectImage = "SELECT VocabImage FROM Vocab WHERE VocabTopic =" + i;
Cursor c = database.rawQuery(selectImage, null);
if(c.moveToFirst())
do{
list.add(c.getBlob(c.getColumnIndex("VocabImage")));
}while(c.moveToNext());
c.close();
return list;
}
This is my java class where I want to call my getImage() method. But there is an error saying that it cannot resolve symbol 'length' in (data.length) in the BitmapFactory line. Anyone has any idea how to solve this? Thank you.
Intent intent = getIntent();
int topicId = intent.getIntExtra("SelectedTopicId", 1);
databaseAccess.open();
List<byte[]>data = databaseAccess.getImage(topicId);
Bitmap image = BitmapFactory.decodeByteArray(data, 0, data.length);
imageView.setImageBitmap(image);
Bitmap image = BitmapFactory.decodeByteArray(data, 0, data.length);
change to
Bitmap image = BitmapFactory.decodeByteArray(data.get(position), 0, data.get(position).length); // pass position for which you want length.
you need to change like this: list.get(0).length for get image at index 0.

How to get image from gallery in a .jpg file format?

I am trying to get image from gallery. It is giving me image as bitmap. I want the image in .jpg file so that I can save file name in my database.
I have followed this tutorial :
http://www.theappguruz.com/blog/android-take-photo-camera-gallery-code-sample
gallery image selected code:
#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();
}
}
Uri selectedImage = data.getData();
String[] filePath = {MediaStore.Images.Media.DATA};
Cursor c = getContentResolver().query(selectedImage, filePath, null, null, null);
c.moveToFirst();
int columnIndex = c.getColumnIndex(filePath[0]);
String picturePath = c.getString(columnIndex);
c.close();
File file = new File(picturePath);// error line
mProfileImage = file;
profile_image.setImageBitmap(bm);
}
I tried this. But I am getting null pointer on file.
Exception :
Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'char[] java.lang.String.toCharArray()' on a null object reference
Also I don't want this newly created file to be saved in external storage. This should be a temporary file. How can I do this?
Thank you..
The good news is you're a lot closer to done than you think!
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
At this point, if bm != null, you have a Bitmap object. Bitmap is Android's generic image object that's ready to go. It's actually probably in .jpg format already, so you just have to write it to a file. you want to write it to a temporary file, so I'd do something like this:
File outputDir = context.getCacheDir(); // Activity context
File outputFile = File.createTempFile("prefix", "extension", outputDir); // follow the API for createTempFile
Regardless, at this point it's pretty easy to write a Bitmap to a file.
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.JPEG, 100, stream); //replace 100 with desired quality percentage.
byte[] byteArray = stream.toByteArray();
Now you have a byte array. I'll leave writing that to a file to you.
If you want the temporary file to go away, see here for more info: https://developer.android.com/reference/java/io/File.html#deleteOnExit()
Bitmap bm=null;
if (data != null) {
try {
bm = MediaStore.Images.Media.getBitmap(getApplicationContext().getContentResolver(), data.getData());
} catch (IOException e) {
e.printStackTrace();
}
}
if (bm != null) { // sanity check
File outputDir = context.getCacheDir(); // Activity context
File outputFile = File.createTempFile("image", "jpg", outputDir); // follow the API for createTempFile
FileOutputStream stream = new FileOutputStream (outputFile, false); // Add false here so we don't append an image to another image. That would be weird.
// This line actually writes a bitmap to the stream. If you use a ByteArrayOutputStream, you end up with a byte array. If you use a FileOutputStream, you end up with a file.
bm.compress(Bitmap.CompressFormat.JPEG, 100, stream);
stream.close(); // cleanup
}
I hope that helps!
Looks like your picturePath is null. That is why you cannot convert the image. Try adding this code fragment to get the path of the selected image:
private String getRealPathFromURI(Uri uri) {
String[] projection = { MediaStore.Images.Media.DATA };
#SuppressWarnings("deprecation")
Cursor cursor = managedQuery(uri, projection, null, null, null);
int column_index = cursor
.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
cursor.moveToFirst();
return cursor.getString(column_index);
}
After that, you need to modify your onSelectFromGalleryResult. Remove/disable line String[] filePath = {MediaStore.Images.Media.DATA}; and so on and replace with below.
Uri selectedImageUri = Uri.parse(selectedImage);
String photoPath = getRealPathFromURI(selectedImageUri);
mProfileImage = new File(photoPath);
//check if you get something like this - file:///mnt/sdcard/yourselectedimage.png
Log.i("FilePath", mProfileImage.getAbsolutePath)
if(mProfileImage.isExist()){
//Check if the file is exist.
//Do something here (display the image using imageView/ convert the image into string)
}
Question: What is the reason you need to convert it in .jpg format? Can it be .gif, .png etc?

BLOB Image from databasetable to Listview

I'm trying to get an image stored as BLOB data in an SQLite database into an Imageview used in a row for a list activity.
This is my code for the two methods I employ to pull regular text data:
private void fillData() {
// TODO Auto-generated method stub
String[] from = new String[] { BorrowMeTable.COLUMN_NAME, BorrowMeTable.COLUMN_DATE };
int[] to = new int[] { R.id.people_list_name, R.id.people_list_borrowed };
getLoaderManager().initLoader(0, null, this);
adapter = new SimpleCursorAdapter(this, R.layout.people_row, null, from,
to, 0);
setListAdapter(adapter);
}
// -----------------------------------------------------------
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
BorrowMeContentProvider.distinctSwitch = true;
String[] projection = { BorrowMeTable.COLUMN_ID, BorrowMeTable.COLUMN_NAME, BorrowMeTable.COLUMN_DATE };
CursorLoader cursorLoader = new CursorLoader(this,
BorrowMeContentProvider.CONTENT_URI, projection, null, null, null);
return cursorLoader;
}
I have another column, BorrowMeTable.COLUMN_IMAGE that I would like to load into my imageView (R.id.pic_of_image). I can't add it to my projection as it cannot be converted to a string. To pull it using a single cursor I would use the code:
byte[] imageByteArray = databaseCursor.getBlob(databaseCursor
.getColumnIndex(BorrowMeTable.COLUMN_IMAGE));
ByteArrayInputStream imageStream = new ByteArrayInputStream(
imageByteArray);
bmp = BitmapFactory.decodeStream(imageStream);
window.setImageBitmap(bmp);
As I have done in another part of my program. Can anyone help as to how I would make this work?
Thanks!
I have another column, BorrowMeTable.COLUMN_IMAGE that I would like to
load into my imageView (R.id.pic_of_image). I can't add it to my
projection as it cannot be converted to a string.
Why do you think so?
If you store images in your database as BLOB data, then you may bravely retrieve them from the DB using their column name in the query projection and after getting the cursor obtain them using Cursor.getBlob(int) method.
You also don't need to input gotten byte array to any byte stream to decode it to a bitmap, because BitmapFactory has decodeByteArray(byte[], int, int) method which allows to decode a byte array to bitmap directly.
The only one thing you should care about is the memory consumption which goes in act when you decode your raw byte arrays to bitmaps.
To work with bitmaps correctly, read this lessons for better explanation.

Categories