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.
Related
I'm trying to save a Image type data as a jpg file to SD card, what I plan to do is first converting it to Bitmap, compress bitmap as jpeg format, then use FileOutputStream to save it to SD card.
Here's my code:
File imagefile = new File(sdCardPath, "image.jpg");
Image image = fromFrame.getImage();
ByteBuffer bbuffer = image.getPlanes()[0].getBuffer();
byte[] byts = new byte[bbuffer.capacity()];
bbuffer.get(byts);
Bitmap bitmapImage = BitmapFactory.decodeByteArray(byts, 0, byts.length, null);
try{
FileOutputStream out = new FileOutputStream(imagefile);
bitmapImage.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (FileNotFoundException e) {
Log.v(TAG, "FileNotFoundExceptionError " + e.toString());
} catch (IOException e) {
Log.v(TAG, "IOExceptionError " + e.toString());
}
It gives error:
java.lang.NullPointerException: Attempt to invoke virtual method 'boolean
android.graphics.Bitmap.compress(android.graphics.Bitmap$CompressFormat,
int, java.io.OutputStream)' on a null object reference
Is there anything I missed or did it wrong?
It turns out that the image file has to be re-organized and as for Depth16 file, every pixel has 16 bits of data, so the code to convert it into a jpg file is:
Image depthimage = fromFrame.getImage();
int imwidth = depthImage.getWidth();
int imheight = depthImage.getHeight();
Image.Plane plane = depthImage.getPlanes()[0];
ShortBuffer shortDepthBuffer = plane.getBuffer().asShortBuffer();
File sdCardFile = Environment.getExternalStorageDirectory();
File file = new File(sdCardFile, "depthImage.jpg");
Bitmap disBitmap = Bitmap.createBitmap(imwidth, imheight, Bitmap.Config.RGB_565);
for (int i = 0; i < imheight; i++) {
for (int j = 0; j < imwidth; j++) {
int index = (i * imwidth + j) ;
shortDepthBuffer.position(index);
short depthSample = shortDepthBuffer.get();
short depthRange = (short) (depthSample & 0x1FFF);
byte value = (byte) depthRange ;
disBitmap.setPixel(j, i, Color.rgb(value, value, value));
}
}
Matrix matrix = new Matrix();
matrix.setRotate(90);
Bitmap rotatedBitmap = Bitmap.createBitmap(disBitmap, 0, 0, imwidth, imheight, matrix, true);
try {
FileOutputStream out = new FileOutputStream(file);
rotatedBitmap.compress(Bitmap.CompressFormat.JPEG, 90, out);
out.flush();
out.close();
MainActivity.num++;
} catch (Exception e) {
e.printStackTrace();
}
} catch (Exception e) {
e.printStackTrace();
}
I also rotate the picture to make it easier to review on mobile devices
I want to compress images that i choose from gallery in android according to there sizes and upload them on to cloud storage. For example if size of an image which i choose is 300kb i don't to reduce it and keep quality 100 but if same is 7Mb i want to reduce it to 10 quality and i want to set max size to 7Mb of the chosen image(original without compression) and similarly puting different conditions on sizes in between.
My code
if (resultCode == RESULT_OK) {
resultUri = result.getUri();
File f = new File(resultUri.getPath());
long sizeUri = f.length()/1024;
try {
bitmap = ImageDecoder.decodeBitmap(ImageDecoder.createSource(getContentResolver(),resultUri));
} catch (IOException e) {
e.printStackTrace();
}
ByteArrayOutputStream baos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, baos);
int baossize= baos.size()/1024;
byte[] uploadbaos = baos.toByteArray();
int lengthbmp = (uploadbaos.length);
int size= lengthbmp/1024;
Log.d(TAG,"baossize: "+baossize+" ByteArray: "+size+" UriSize: "+sizeUri);
// UploadingImage();
}
Just do it:
int quality;
if (sizeUri <= 300)
quality = 90;
else if (sizeUri <= 1000)
quality = 80;
else if (sizeUri <= 2000)
quality = 70;
else if (sizeUri <= 3000)
quality = 50;
else
quality = 30;
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, baos);
Note that JPEG quality 100 is probably too high and below 30 can be very blurry.
Here in the given example you can set the max size , like in your case it could be 7MB.
public static boolean reduceImage(String path, long maxSize) {
File img = new File(path);
boolean result = false;
BitmapFactory.Options options = new BitmapFactory.Options();
Bitmap bitmap = null;
options.inSampleSize=1;
while (img.length()>maxSize) {
options.inSampleSize = options.inSampleSize+1;
bitmap = BitmapFactory.decodeFile(path, options);
img.delete();
try
{
FileOutputStream fos = new FileOutputStream(path);
img.compress(path.toLowerCase().endsWith("png")?
Bitmap.CompressFormat.PNG:
Bitmap.CompressFormat.JPEG, 100, fos);
fos.close();
result = true;
}catch (Exception errVar) {
errVar.printStackTrace();
}
};
return result;
}
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;
}
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;
}
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.