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.
Related
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);
}
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?
I have a list of mp4 files that i need to extract a thumbnail for each one.
Thumbnail criteria:
The thumbnail must be in Base64 format
The thumbnail has a specific size which will be provided as a method parameter
It must be extracted from the frame in the middle of the file (e.g. if the video duration is 10s then the thumbnail must be from the frame in 5th second.
1 and 2 are currently achieved but I'm not sure how to do 3.
This is my code:
public static String getVideoDrawable(String path, int height, int width) throws OutOfMemoryError{
try {
Bitmap bitmap = ThumbnailUtils.createVideoThumbnail(path, android.provider.MediaStore.Images.Thumbnails.MINI_KIND);
bitmap = Bitmap.createScaledBitmap(bitmap, height, width, false);
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, byteArrayOutputStream);
byte[] byteArray = byteArrayOutputStream .toByteArray();
return Base64.encodeToString(byteArray, Base64.DEFAULT);
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
You need to use the MediaMetadataRetriever for that.
MediaMetadataRetriever metadataRetriever = new MediaMetadataRetriever();
try {
metadataRetriever.setDataSource(path);
String duration=metadataRetriever.extractMetadata(MediaMetadataRetriever.METADATA_KEY_DURATION);
long time=Long.valueOf(duration)/2;
Bitmap bitmap = metadataRetriever.getFrameAtTime(time,MediaMetadataRetriever.OPTION_NEXT_SYNC);
//now convert to base64
} catch (Exception ex) {
}
http://developer.android.com/intl/es/reference/android/media/MediaMetadataRetriever.html#getFrameAtTime%28long,%20int%29
Here's the code that saves an image file to... somewhere? How do I get the URI for the file "webimage"?
Bitmap bmp = ((BitmapDrawable)imageView.getDrawable()).getBitmap();
String fileName = "webImage";//no .png or .jpg needed
try {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
FileOutputStream fo = openFileOutput(fileName, Context.MODE_PRIVATE);
fo.write(bytes.toByteArray());
// remember close file output
fo.close();
} catch (Exception e) {
e.printStackTrace();
}
Use getFileStreamPath() like this:
String fileName = "webImage";
//...
Uri uri = Uri.fromFile(getFileStreamPath(fileName));
Figured it out I think:
final File file = new File(getFilesDir(), "webImage");
Uri weburi = Uri.fromFile(file);
You can use Uri.fromFile(imageFile), where imageFile is an instance of File
I am trying to open an image I have stored on external memory. Here is the code I have:
File imagePath = new File(imageURI);
InputStream inputStream=null;
try {
inputStream = getContentResolver().openInputStream(Uri.parse(imageURI));
}catch(FileNotFoundException e){
e.printStackTrace();
}
Bitmap bm = BitmapFactory.decodeStream(inputStream);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] originalImage = baos.toByteArray();
But it doesn't seem to be able to locate the file. The Uri is in the format content://com.android.providers.media.documents/document/image%3A21.
Thanks for any help.
In a project I am working on now I have external images in a directory on the SD card. I am using
String thePath = Environment.getExternalStorageDirectory() + "/myAppFiles”;
File imgFile = new File(thePath + " / " + "
externalImage.jpg ");
if (imgFile.exists()) {
try {
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 6;
Bitmap bm = BitmapFactory.decodeFile(imgFile.getAbsolutePath(), options);
}
}
Try this:
File imagePath = new File(imageURI.getPath());
url.getPath() returns a String in the following format: "/mnt/sdcard/xxx.jpg", without the scheme type pre-fixed