How to obtain thumbnail path from image path in android? - java

Basically i have image path that looks like this: /mnt/sdcard/Pictures/image.jpg
And i need to get a path to thumbnail from it, in a fastest possible way.
I am trying to use MediaStore.Images.Thumbnails.queryMiniThumbnail, but no matter what i pass i get null cursor.
Thanks!
EDIT:
This is the function that brings ALL of the image paths and thumbnail paths and stores them in a String. What I need is a function that returns thumbnail path for a specific image path (/mnt/sdcard/Pictures/image.jpg). Thanks
public String getThumbPaths(ThumbContext ctx) {
Uri uri = MediaStore.Images.Thumbnails.getContentUri("external");
Cursor cursor = MediaStore.Images.Thumbnails.queryMiniThumbnails(ctx
.getActivity().getContentResolver(), uri,
MediaStore.Images.Thumbnails.MINI_KIND, null);
int columnIndex = cursor.getColumnIndex(Thumbnails.IMAGE_ID);
String[] filePathColumn = { MediaStore.Images.Media.DATA };
StringBuilder stringBuilder = new StringBuilder();
String id = MediaStore.Images.Media._ID + "=?";
String orientation="1";
for (cursor.moveToFirst(); !cursor.isAfterLast(); cursor.moveToNext()) {
String imageId = cursor.getString(columnIndex);
Cursor images = ctx.getActivity().managedQuery(
MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
filePathColumn, id,
new String[] { imageId }, null);
String filePath = "";
if (images != null && images.moveToFirst()) {
filePath = images.getString(images
.getColumnIndex(filePathColumn[0]));
}
ExifInterface exifReader;
try {
exifReader = new ExifInterface(filePath);
orientation=exifReader.getAttribute(ExifInterface.TAG_ORIENTATION);
} catch (IOException e) {
// TODO Auto-generated catch block
//e.printStackTrace();
}
stringBuilder.append(cursor.getString(1) + ";");
stringBuilder.append(filePath + ";");
stringBuilder.append(orientation + ";");
orientation="1";
}
//cursor.close();
return stringBuilder.toString();
}

If i understand it right, your image is not in the Media database. You can use
ThumbnailUtils.extractTumbnail()
which requires only a Bitmap.

Try it out. it will help you to set the Thumbnail of image set to ImageView.
im=(ImageView)findViewById(R.id.imageView1);
byte[] imageData = null;
try
{
final int THUMBNAIL_SIZE = 64;
//InputStream is=getAssets().open("apple-android-battle.jpg");
FileInputStream fis = new FileInputStream("/sdcard/apple.jpg");
Bitmap imageBitmap = BitmapFactory.decodeStream(fis);
Float width = new Float(imageBitmap.getWidth());
Float height = new Float(imageBitmap.getHeight());
Float ratio = width/height;
imageBitmap = Bitmap.createScaledBitmap(imageBitmap, (int)(THUMBNAIL_SIZE * ratio), THUMBNAIL_SIZE, false);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
imageBitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
imageData = baos.toByteArray();
im.setImageBitmap(imageBitmap);
}
catch(Exception ex) {
}
Hope it will help you.

Related

Failing to download image and store as bitmap on android

I am trying to download an image from the internet and save it to my internal storage to be used elsewhere in my app. However the image that is received fails to compress and save. bitmap.compress(Bitmap.CompressFormat.JPEG, 70, out); throws a nullpointer. Any help is appreciated.
private String SaveImage(String imageURL) {
Bitmap bitmap = null;
try {
// Download Image from URL
URL testUrl = new URL(imageURL);
URLConnection urlConnection = testUrl.openConnection();
HttpURLConnection httpURLConnection = (HttpURLConnection) urlConnection;
InputStream is = httpURLConnection.getInputStream();
// Decode Bitmap
BitmapFactory.Options options = new BitmapFactory.Options();
options.inJustDecodeBounds = true;
BitmapFactory.decodeStream(is, null, options);
Boolean scaleByHeight = Math.abs(options.outHeight - 300) >= Math.abs(options.outWidth - 300);
if(options.outHeight * options.outWidth * 2 >= 200*200*2){
// Load, scaling to smallest power of 2 that'll get it <= desired dimensions
double sampleSize = scaleByHeight
? options.outHeight / 300
: options.outWidth / 300;
options.inSampleSize =
(int)Math.pow(2d, Math.floor(
Math.log(sampleSize)/Math.log(2d)));
}
// Do the actual decoding
options.inJustDecodeBounds = false;
is.close();
is = httpURLConnection.getInputStream();
bitmap = BitmapFactory.decodeStream(is, null, options);
is.close();
String root = getApplicationContext().getFilesDir().toString();
File myDir = new File(root + "/saved_images");
myDir.mkdirs();
Random generator = new Random();
int n = 100000;
n = generator.nextInt(n);
String fname = "Image-" + n + ".png";
File file = new File(myDir, fname);
if (file.exists()) file.delete();
FileOutputStream out = new FileOutputStream(file);
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, out); //here
out.flush();
out.close();
return getApplicationContext().getFilesDir().toString() + "/saved_images/" + "Image-" + n + ".png";
} catch (IOException e) {
e.printStackTrace();
}
return null;
}

how convert multiple images to single PDF from folder in android?

I want to make android app to merge multiple image from single folder into single pdf file.
ex :
folder name :
- images
- 1.jpg
- 2.jpg
- 3.jpg
- 4.jpg
- 5.jpg
there are 5 images are in folder named images
how can i make pdf of that images?
if anyone have possible solution then please comment answer :)
Try this after 4.4 version it will work.
private void createPDF() {
final File file = new File(uploadFolder, "AnswerSheet_" + queId + ".pdf");
final ProgressDialog dialog = ProgressDialog.show(this, "", "Generating PDF...");
dialog.show();
new Thread(() -> {
Bitmap bitmap;
PdfDocument document = new PdfDocument();
// int height = 842;
//int width = 595;
int height = 1010;
int width = 714;
int reqH, reqW;
reqW = width;
for (int i = 0; i < array.size(); i++) {
// bitmap = BitmapFactory.decodeFile(array.get(i));
bitmap = Utility.getCompressedBitmap(array.get(i), height, width);
reqH = width * bitmap.getHeight() / bitmap.getWidth();
Log.e("reqH", "=" + reqH);
if (reqH < height) {
// bitmap = Bitmap.createScaledBitmap(bitmap, reqW, reqH, true);
} else {
reqH = height;
reqW = height * bitmap.getWidth() / bitmap.getHeight();
Log.e("reqW", "=" + reqW);
// bitmap = Bitmap.createScaledBitmap(bitmap, reqW, reqH, true);
}
// Compress image by decreasing quality
// ByteArrayOutputStream out = new ByteArrayOutputStream();
// bitmap.compress(Bitmap.CompressFormat.WEBP, 50, out);
// bitmap = BitmapFactory.decodeStream(new ByteArrayInputStream(out.toByteArray()));
//bitmap = bitmap.copy(Bitmap.Config.RGB_565, false);
//Create an A4 sized page 595 x 842 in Postscript points.
//PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(595, 842, 1).create();
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(reqW, reqH, 1).create();
PdfDocument.Page page = document.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Log.e("PDF", "pdf = " + bitmap.getWidth() + "x" + bitmap.getHeight());
canvas.drawBitmap(bitmap, 0, 0, null);
document.finishPage(page);
}
FileOutputStream fos;
try {
fos = new FileOutputStream(file);
document.writeTo(fos);
document.close();
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
runOnUiThread(() -> {
dismissDialog(dialog);
});
}).start();
}
If you want to create a pdf file with multiple images you can use PdfDocument from Android. Here is a demo:
private void createPDFWithMultipleImage(){
File file = getOutputFile();
if (file != null){
try {
FileOutputStream fileOutputStream = new FileOutputStream(file);
PdfDocument pdfDocument = new PdfDocument();
for (int i = 0; i < images.size(); i++){
Bitmap bitmap = BitmapFactory.decodeFile(images.get(i).getPath());
PdfDocument.PageInfo pageInfo = new PdfDocument.PageInfo.Builder(bitmap.getWidth(), bitmap.getHeight(), (i + 1)).create();
PdfDocument.Page page = pdfDocument.startPage(pageInfo);
Canvas canvas = page.getCanvas();
Paint paint = new Paint();
paint.setColor(Color.BLUE);
canvas.drawPaint(paint);
canvas.drawBitmap(bitmap, 0f, 0f, null);
pdfDocument.finishPage(page);
bitmap.recycle();
}
pdfDocument.writeTo(fileOutputStream);
pdfDocument.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
private File getOutputFile(){
File root = new File(this.getExternalFilesDir(null),"My PDF Folder");
boolean isFolderCreated = true;
if (!root.exists()){
isFolderCreated = root.mkdir();
}
if (isFolderCreated) {
String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.US).format(new Date());
String imageFileName = "PDF_" + timeStamp;
return new File(root, imageFileName + ".pdf");
}
else {
Toast.makeText(this, "Folder is not created", Toast.LENGTH_SHORT).show();
return null;
}
}
Here images is the ArrayList of the images with path.
Break your problem down into smaller problems. It's a fairly simple application.
Get the folder name from the user. See the native file open dialog to find a folder. See here.
Search its files for images
Create a pdf of the images. Use a library such as apache pdfbox.
Use this iText library
Create a document
String FILE = "{folder-path}/FirstPdf.pdf";
Document document = new Document();
PdfWriter.getInstance(document, new FileOutputStream(FILE));
document.open();
Add image in the document
try {
// get input stream
String fileName = "OfflineMap/abc.jpg";
String path =
Environment.getExternalStorageDirectory()+"/"+fileName;
File file = new File(path);
FileInputStream fileInputStream = new FileInputStream(file);
InputStream ims = getAssets().open("myImage.png");
Bitmap bmp = BitmapFactory.decodeStream(ims);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
document.add(image);
document.close();
}
catch(IOException ex)
{
return;
}

Getting RGB byte array from Bitmap Android

I'm try to get a byte array from a picture stored on an android device, but the byte array size is width * heigth * 2, and I need a byte array of the size width * heigth * 3.
My problem is that I need to send a picture byte array to a matlab server that need the array in this RGB format.
Here is the code that creates a byte array of "width * height" size:
Bitmap photo = BitmapHelper.readBitmap(CameraIntentActivity.this, photoUri);
if (photo != null) {
photo = BitmapHelper.shrinkBitmap(photo, 300, rotateXDegrees);
Bitmap bm = Bitmap.createScaledBitmap(photo, 640, 480, true);
final int lnth= bm.getByteCount();
ByteBuffer dst= ByteBuffer.allocate(lnth);
bm.copyPixelsToBuffer( dst);
byte[] byteArray = dst.array();
The readBitmap method:
public static Bitmap readBitmap(Context context, Uri selectedImage) {
Bitmap bm = null;
BitmapFactory.Options options = new BitmapFactory.Options();
options.inPreferredConfig = Bitmap.Config.RGB_565;
options.inScaled = false;
AssetFileDescriptor fileDescriptor = null;
try {
fileDescriptor = context.getContentResolver().openAssetFileDescriptor(selectedImage, "r");
} catch (FileNotFoundException e) {
return null;
} finally {
try {
bm = BitmapFactory.decodeFileDescriptor(
fileDescriptor.getFileDescriptor(), null, options);
fileDescriptor.close();
} catch (IOException e) {
return null;
}
}
return bm;
}

Images compressing with wrong colors

I using java code for compressing images. Sometimes i am getting image with wrong colors. I don't understand why it's beheviour is inconsistent.
Images downloading from urls
public void imageDownload() {
String key = (String) map.get("key");
String url = (String) map.get("url");
**String imagePath = java.util.UUID.randomUUID() + ".jpg";
String compressedImage = Constant.COMPRESSED + imagePath;**
try {
URL url = new URL(url);
InputStream is = url.openStream();
// Stream to the destionation file
FileOutputStream fos = new FileOutputStream(imagePath);
// Read bytes from URL to the local file
byte[] buffer = new byte[4096];
int bytesRead = 0;
while ((bytesRead = is.read(buffer)) != -1)
fos.write(buffer, 0, bytesRead);
// Close destination stream
fos.close();
// Close URL stream
is.close();
compressFile(imagePath, compressedImage, key);
} catch (Exception exception) {
log.debug("Exception occured while downloading images..." + exception.getLocalizedMessage());
}
}
}
Image compression code
private void compressFile(final String inputFilePath, final String outputFilePath,final String fileKey) {
log.debug("Image file name::" + outputFilePath);
log.debug("Image key is::" + fileKey);
final String outputImagePath = tempFilePath + outputFilePath;
final File inputFile = new File(inputFilePath);
float quality = FileUpload.getQuality(inputFile);
log.debug("Image size for url is::" + inputFile.length() + "quality constent::" + quality);
final File outputFile = new File(outputImagePath);
boolean s3Uploaded = true;
if (quality != 0.0f) {
final boolean isCompressed = FileUpload.fileCompress(inputFile, outputFile, quality);
}
}
Compression code
public static boolean fileCompress(File inputFilePath, File outputFilePath, float quality) {
log.debug("File compress with path::" + inputFilePath + "output file path" + outputFilePath);
boolean isCompressed = false;
OutputStream os = null;
ImageOutputStream ios = null;
ImageWriter writer = null;
try {
BufferedImage image = ImageIO.read(inputFilePath);
os = new FileOutputStream(outputFilePath);
Iterator<ImageWriter> writers = ImageIO.getImageWritersByFormatName("jpg");
writer = (ImageWriter) writers.next();
ios = ImageIO.createImageOutputStream(os);
writer.setOutput(ios);
ImageWriteParam param = writer.getDefaultWriteParam();
param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
param.setCompressionQuality(quality);
writer.write(null, new IIOImage(image, null, null), param);
os.close();
ios.close();
writer.dispose();
isCompressed = true;
} catch (Exception exception) {
log.error("File could not compress due to " + exception.getCause());
isCompressed= false;
}
return isCompressed;
}
getting quality parameter
public static float getQuality(File input) {
long size = input.length();
log.debug("getting quality constant on the basis of image size: " + size);
if (size > 768000) {
return 0.3f;
}
if (size > 512000 && size <= 768000) {
return 0.6f;
}
if (size > 256000 && size <= 512000) {
return 0.7f;
}
if (size > 51200) {
return 0.9f;
}
return 0.0f;
}
Destroyed image(image size was before compressing - 84616)
Thanks

Image orientation changed while uploading to amazon server

I am uploading an image to the amazon server. Everything works well but only on few devices the orientation changes to landscape. At the time of uploading the orientation changes on a few Samsung devices and tablets. I have tried to fix it but nothing seems to be working. Below mentioned is my code.
if (requestCode == CAPTURE_IMAGE_ACTIVITY_REQUEST_CODE) {
if (resultCode == RESULT_OK) {
value = true;
viewPager.setVisibility(View.VISIBLE);
Uri takenPhotoUri = getPhotoFileUri(photoFileName); //get the uri of the photo in order to get the path.
System.out.println("URI==" + takenPhotoUri);
al.add(takenPhotoUri);
Bitmap takenImage = BitmapFactory.decodeFile(takenPhotoUri.getPath());
final int maxSize = 1560;
int outWidth, outHeight;
int inWidth = takenImage.getWidth();
int inHeight = takenImage.getHeight();
if (inWidth > inHeight) {
outHeight = maxSize;
outWidth = (inHeight * maxSize) / inWidth;
} else {
outHeight = maxSize;
outWidth = (inWidth * maxSize) / inHeight;
}
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
takenImage = Bitmap.createScaledBitmap(takenImage, outWidth, outHeight, false);
String newDate = sdf.format(new Date());
Canvas canvas = new Canvas(takenImage); //bmp is the bitmap to dwaw into
Paint paint = new Paint();
paint.setColor(Color.RED);
paint.setTextSize(30);
paint.setTextAlign(Paint.Align.RIGHT);
canvas.drawText(newDate, 200, 100, paint);
//Creating a byte array output stream which is used to store the image once it has been compressed.
ByteArrayOutputStream bos = new ByteArrayOutputStream();
//Compress the image and store it in our ByteArrayOutPutStream
takenImage.compress(Bitmap.CompressFormat.JPEG, 90, bos);
int rotate = 0;
try {
getContentResolver().notifyChange(takenPhotoUri, null);
File imageFile = new File(String.valueOf(al.get(0)));
ExifInterface exif = new ExifInterface(
imageFile.getAbsolutePath());
int orientation = exif.getAttributeInt(
ExifInterface.TAG_ORIENTATION,
ExifInterface.ORIENTATION_NORMAL);
switch (orientation) {
case ExifInterface.ORIENTATION_ROTATE_270:
rotate = 270;
break;
case ExifInterface.ORIENTATION_ROTATE_180:
rotate = 180;
break;
case ExifInterface.ORIENTATION_ROTATE_90:
rotate = 90;
break;
}
Matrix matrix = new Matrix();
matrix.postRotate(rotate);
} catch (Exception e) {
e.printStackTrace();
}
try {
s3Client = new AmazonS3Client(
new BasicAWSCredentials(MY_ACCESS_KEY_ID, MY_SECRET_KEY));
byte[] contentBytes = bos.toByteArray(); //Create a byte array to store the size of the stream.
is = new ByteArrayInputStream(contentBytes);
Long contentLength = Long.valueOf(contentBytes.length);
objectMetadata = new ObjectMetadata();
objectMetadata.setContentLength(contentLength);
myAsyncTask = new MyAsyncTask();
myAsyncTask.execute();
responseUrl += s3Client.getResourceUrl(BUCKET_NAME, photoFileName) + " ";
System.out.println("URL IS +==========" + responseUrl);
} catch (Exception e) {
e.printStackTrace();
}
//Add the path of the image to the array list and pass it to our custom adapter.
bitmapArrayList.add(takenImage);
imageSwipeAdapter = new ImageSwipeAdapter(this, iv, bitmapArrayList, viewPager, this, al,
viewPagerLayout, cameraBtn);
viewPager.setAdapter(imageSwipeAdapter);
} else {
Toast.makeText(this, "Picture Wasn't taken!", Toast.LENGTH_SHORT).show();
}
My AsyncTask is uploading the image in the background.

Categories

Resources