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

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

Related

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.

How do I compress image when uploading to server?

I have been trying to look at other examples for compression of images. However, I still don't know where and how do I include the codes for compression into. Could anybody help me with this?
public void uploadMultipart() {
//getting name for the image
String name = editText.getText().toString().trim();
//getting the actual path of the image
String path = getPath(filePath);
//Uploading code
try {
String uploadId = UUID.randomUUID().toString();
//Creating a multi part request
new MultipartUploadRequest(this, uploadId, Constants.UPLOAD_URL)
.addFileToUpload(path, "image") //Adding file
.addParameter("name", name) //Adding text parameter to the request
.setNotificationConfig(new UploadNotificationConfig())
.setMaxRetries(2)
.startUpload(); //Starting the upload
} catch (Exception exc) {
Toast.makeText(this, exc.getMessage(), Toast.LENGTH_SHORT).show();
}
}
//method to get the file path from uri
public String getPath(Uri uri) {
Cursor cursor = getContentResolver().query(uri, null, null, null, null);
cursor.moveToFirst();
String document_id = cursor.getString(0);
document_id = document_id.substring(document_id.lastIndexOf(":") + 1);
cursor.close();
cursor = getContentResolver().query(
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
null, MediaStore.Images.Media._ID + " = ? ", new String[]{document_id}, null);
cursor.moveToFirst();
String path = cursor.getString(cursor.getColumnIndex(MediaStore.Images.Media.DATA));
// Bitmap bmp = BitmapFactory.decodeFile(path);
// ByteArrayOutputStream baos = new ByteArrayOutputStream();
// bmp.compress(Bitmap.CompressFormat.JPEG, 100, baos);
cursor.close();
return path;
}
Here is the code for compress image in Bitmap
Below code for jpeg images
Bitmap bitmap = BitmapFactory.decodeStream(getAssets().open("imagename.png"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 90, out); // you can set as 90 for compress ration
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
Below code for png images:
Bitmap bitmap= BitmapFactory.decodeStream(getAssets().open("imagename.png"));
ByteArrayOutputStream out = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 90, out);
Bitmap decoded = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
Otherwise, Here is code which encode the string and send to server as encoded format image
String encodedString ="";
try {
BitmapFactory.Options options = null;
options = new BitmapFactory.Options();
options.inSampleSize = 1;
bitmap = BitmapFactory.decodeFile(filepath, options);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
// Must compress the Image to reduce image size to make upload easy
bitmap.compress(Bitmap.CompressFormat.PNG, 90, stream);
byte[] byte_arr = stream.toByteArray();
// Encode Image to String
encodedString = Base64.encodeToString(byte_arr, 0);
} catch (Exception e) {
e.printStackTrace();
}
Try to above solution. It will work for me.

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?

how to check image size less then 100kb android

I am trying to get image from gallery and setting up it on ImageView , Hear is okay well i get and set image on ImageView, but now i want to check image size of selected image in kb so i set the validaion for image uploading.
Please anyone can suggest me how to check selected image size less then 100kb or not?,
Hear is my code for image selecting and setting it.
Choosing Image useing Intent
Intent iv = new Intent(
Intent.ACTION_PICK,
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(iv, RESULT_LOAD_IMAGE);
and get Image Result code ..
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if (requestCode == RESULT_LOAD_IMAGE && resultCode == RESULT_OK && 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]);
picturePath = cursor.getString(columnIndex);
cursor.close();
Bitmap bmp=BitmapFactory.decodeFile(picturePath);
ivLogo.setImageBitmap(bmp);
uploadNewPic();
}
}
to know the size is less then 100kb. you should know the image size to compare. there is some method to know the size of bitmap
method 1
Bitmap bitmapOrg = BitmapFactory.decodeResource(getResources(),
R.drawable.ic_launcher);
Bitmap bitmap = bitmapOrg;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, stream);
byte[] imageInByte = stream.toByteArray();
long lengthbmp = imageInByte.length;
method 2
File file = new File("/sdcard/Your_file");
long length = file.length() / 1024; // Size in KB
For more Study
go for http://developer.android.com/reference/android/graphics/Bitmap.html#getByteCount%28%29
Get file size as
File img = new File(picturePath);
int length = img.length();
it will return size in bytes. you can convert byte into kb
ArrayList<String> filePaths = new ArrayList<>();
ArrayList<String> newFilePath = new ArrayList<>(); //for storing file path which size is less than 100 KB
if (imagePaths != null) {
filePaths.addAll(imagePaths);
for (int i = 0; i < filePaths.size(); i++) {
File file = new File(filePaths.get(i));
int file_size = Integer.parseInt(String.valueOf(file.length() / 1024)); //calculate size of image in KB
if (file_size < 100)
newFilePath.add(filePaths.get(i)); //if file size less than 100 KB then add to newFilePath ArrayList
}
}
Here imagePaths stores path of all images that we have selected. Then if imagePaths is not null then add all images path in filePaths. You can use this code for document type of file also.
Just input URI from the intent and get the size of any file
uri = data.getData();
Cursor returnCursor = getContentResolver().query(uri, null, null, null, null);
int nameIndex = returnCursor.getColumnIndex(OpenableColumns.DISPLAY_NAME);
int sizeIndex = returnCursor.getColumnIndex(OpenableColumns.SIZE);
returnCursor.moveToFirst();
Log.e("TAG", "Name:" + returnCursor.getString(nameIndex));
Log.e("TAG","Size: "+Long.toString(returnCursor.getLong(sizeIndex)));
It will give size in bytes, So 100kb will be 100000bytes. I think this will help you.

Convert Byte to Bitmap

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

Categories