I am trying to creating pdfs from images in my Android application.
I get the image successfully and created the pdf file successfully. But When I open my pdf file, images are not displayed. I have tried many solutions on Internet but all in vain.
I am pasting my code. Kindly guide me.
First I am pasting the code for getting image from gallery
Intent myIntent = new Intent(Intent.ACTION_PICK,
MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
startActivityForResult(myIntent,120);
Now I am pasting the code of OnActivityResult Method, in which I am getting the image and craeating a pdf file.
try {
Document doc = new Document();
if (resultCode == RESULT_OK) {
if (requestCode == 120) {
if (data.getData() != null) {
Uri uri = data.getData();
Image image = Image.getInstance(uri.toString());
FileOutputStream fileOutputStream =openFileOutput("mypdf.pdf", Context.MODE_PRIVATE);
PdfWriter.getInstance(doc, fileOutputStream);
doc.open();
doc.add(image);
doc.close();
}
}
}
} catch (IOException | DocumentException e) {
e.printStackTrace();
}
As you are using iText you need to create BitMap format of image and then need to add into pdf.
ByteArrayOutputStream stream = new ByteArrayOutputStream();
Bitmap bitmap = MediaStore.Images.Media.getBitmap(contentResolver, <pass the uri of image>);
bitmap.compress(Bitmap.CompressFormat.JPEG, 100 , stream);
Image myImg = Image.getInstance(stream.toByteArray());
myImg.setAbsolutePosition(470f,755f);
myImg.scaleToFit(100f,100f);
document.add(myImg);
I have solved it, The solution was to use Input Stream as follows:
Uri uri = data.getData();
InputStream ims = getContentResolver().openInputStream(uri);
Bitmap bitmap = BitmapFactory.decodeStream(ims);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] byteArray = stream.toByteArray();
Image image = Image.getInstance(byteArray);
doc.add(image);
doc.close();
Related
While I select the image from the gallery and shows it in ImageView. The image quality is all right. But, uploading an image on the server, it lost quality and become a blur. I obtain the image from the camera by this code.
private void onCaptureImageResult(Intent data) {
bitmap = (Bitmap) data.getExtras().get("data");
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
File destination = new File(
Environment.getExternalStorageDirectory(),
System.currentTimeMillis() + ".jpg"
);
FileOutputStream fo;
try {
destination.createNewFile();
fo = new FileOutputStream(destination);
fo.write(bytes.toByteArray());
fo.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
imageView.setImageBitmap(bitmap);
}
Then, I did this work-
private String imageToString(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG,100,byteArrayOutputStream);
byte[] imgByte=byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imgByte,Base64.DEFAULT);
}
and used this function to compress my selected photo. But, it makes the loss of that image quality and image become a blur on the server. Why am I facing this problem?
You could use the .png format as it's lossless and doesn't reduce the image quality. On the other hand the .jpeg format is just the opposite of this.
private String imageToString(Bitmap bitmap){
ByteArrayOutputStream byteArrayOutputStream=new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, byteArrayOutputStream);
byte[] imgByte=byteArrayOutputStream.toByteArray();
return Base64.encodeToString(imgByte, Base64.DEFAULT);
}
You did not show the intent to start a Camera app.
But you did it in such a way that you only got a thumbnail of the picture taken.
Change the intent. Add an uri where the camera app can save the full picture.
There are 783 examples of such an intent on stackoverflow and even more on the internet.
I am trying to save a bitmap which user selects into my own App path.
Unfortunately, with very big images I get OutOfMemoryError error.
I am using the following code:
private String loadImage (Uri filePath) {
File fOut = new File(getFilesDir(),"own.jpg");
inStream = getContentResolver().openInputStream(filePath);
selectedImage = BitmapFactory.decodeStream(inStream);
selectedImage.compress(CompressFormat.JPEG, 100, new FileOutputStream(fOut));
}
Is there any way for me to save any image file of any size for an Uri to a file?
*I am not in a position to resize the image e.g. by using calculateInSampleSize method.
Is there any way for me to save any image file of any size for an Uri to a file?
Since it already is an image, just copy the bytes from the InputStream to the OutputStream:
private void copyInputStreamToFile( InputStream in, File file ) {
try {
FileOutputStream out = new FileOutputStream(file);
byte[] buf = new byte[8192];
int len;
while((len=in.read(buf))>0){
out.write(buf,0,len);
}
out.flush();
out.getFD().sync();
out.close();
in.close();
} catch (Exception e) {
e.printStackTrace();
}
}
(adapted from this SO answer)
I've got an Image Uri, retrieved using the following:
public Uri getImageUri(Context inContext, Bitmap inImage) {
ByteArrayOutputStream bytes = new ByteArrayOutputStream();
inImage.compress(Bitmap.CompressFormat.JPEG, 100, bytes);
String path = Images.Media.insertImage(inContext.getContentResolver(), inImage, "Title", null);
return Uri.parse(path);
}
This works just amazing for Intents that require an Image URI, etc (so I know for sure the URI is valid).
But now I want to save this Image URI to a file on the SDCARD. This is more difficult because the URI does not really point at a file on the SDCARD or the app.
Will I have to create a bitmap from the URI first, and then save the Bitmap on the SDCARD or is there a quicker way (preferable one that does not require the conversion to a bitmap first).
(I've had a look at this answer, but it returns file not found - https://stackoverflow.com/a/13133974/1683141)
The problem is that the Uri you've been given by Images.Media.insertImage() isn't to an image file, per se. It is to a database entry in the Gallery. So what you need to do is read the data from that Uri and write it out to a new file in the external storage using this answer https://stackoverflow.com/a/8664605/772095
This doesn't require creating a Bitmap, just duplicating the data linked to the Uri into a new file.
You can get the data using an InputStream using code like:
InputStream in = getContentResolver().openInputStream(imgUri);
Update
This is completely untested code, but you should be able to do something like this:
Uri imgUri = getImageUri(this, bitmap); // I'll assume this is a Context and bitmap is a Bitmap
final int chunkSize = 1024; // We'll read in one kB at a time
byte[] imageData = new byte[chunkSize];
try {
InputStream in = getContentResolver().openInputStream(imgUri);
OutputStream out = new FileOutputStream(file); // I'm assuming you already have the File object for where you're writing to
int bytesRead;
while ((bytesRead = in.read(imageData)) > 0) {
out.write(Arrays.copyOfRange(imageData, 0, Math.max(0, bytesRead)));
}
} catch (Exception ex) {
Log.e("Something went wrong.", ex);
} finally {
in.close();
out.close();
}
I want to add image to android PDF using iText. I want to achieve this without saving image to SDCard first. I put my image into res/drawable folder but proving the image path doesn’t work and it throws FileNotFound Exception. My path is like this:
String path = “res/drawable/myImage.png”
Image image = Image.getInstance(path);
document.add(image);
Now please suggest me a solution how I will add correct file path to getInstance(…) method. Thanks
Of course it'll not work at that way.
move your image to assets folder to access it with getassets() method
// load image
try {
// get input stream
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);
}
catch(IOException ex)
{
return;
}
I found a solution for your issue. If you want to get image from your drawable folder and put it into a PDF file using iText use this code:
try {
document.open();
Drawable d = getResources().getDrawable(R.drawable.myImage);
BitmapDrawable bitDw = ((BitmapDrawable) d);
Bitmap bmp = bitDw.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
document.add(image);
document.close();
} catch (Exception e) {
e.printStackTrace();
}
Here is the code to add image to PDF using iText, if the image is dynamic (i.e), if the image cannot be added to asset folder at compile time,
public void addImage(Document document,ImageView ivPhoto) throws DocumentException {
try {
BitmapDrawable drawable = (BitmapDrawable) ivPhoto.getDrawable();
Bitmap bitmap = drawable.getBitmap();
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 100, stream);
byte[] imageInByte = stream.toByteArray();
Image image = Image.getInstance(imageInByte);
document.add(image);
}
catch(IOException ex)
{
return;
}
}
Here is my code, To set Image on particular position
move your image to assets folder to get image by getassets() method.
Hope this will help you!
try {
InputStream ims = getAssets().open("header1.png");
Bitmap bmp = BitmapFactory.decodeStream(ims);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bmp.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
image.setAbsolutePosition(10f,750f);
image.scaleToFit(850,78);
document.add(image);
}
catch(IOException ex)
{
ex.printStackTrace();
return;
}
try {
FileInputStream in = new FileInputStream("input file uri");
PdfReader pdfReader = new PdfReader(in);
PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileOutputStream("output file uri"));
PdfContentByte content = pdfStamper.getOverContent(1);
Image deliverImg = Image.getInstance("image URI");
deliverImg.setAbsolutePosition(420f, 100f);
content.addImage(deliverImg);
pdfStamper.close();
} catch (DocumentException de) {
Log.e("PDFCreator", "DocumentException:" + de);
} catch (IOException e) {
Log.e("PDFCreator", "ioException:" + e);
}
I have the following:
A very long URL of where the image is located (on the internet)
String imageAddress = data.getExtras().get("imageHTTP").toString();
The returns fine and there is an image ending with .jpg
The next part is where I'm having problems.
Basically I've got a crop intent that accepts Uri's but the following doesn't work:
Uri imageUri = Uri.parse(imageAddress);
Intent intent = new Intent(this, com.android.camera.CropImage.class);
intent.setData(uri);
intent.putExtra("return-data", true);
startActivityForResult(intent, CROP);
Any ideas?
Following error code:
got exception decoding bitmap
java.lang.NullPointerException
at com.android.camera.Util.makeInputStream(Util.java:337)
I figured this out. Was easier to save it to sdcard temporary then crop, then delete the temporary one. After that I ran it though a downloaded crop library (don't know where downloaded it from but there are a few).
File file = null;
try {
URL myImageURL = new URL(imagePath);
HttpURLConnection connection = (HttpURLConnection)myImageURL.openConnection();
connection.setDoInput(true);
connection.connect();
InputStream input = connection.getInputStream();
// Get the bitmap
Bitmap myBitmap = BitmapFactory.decodeStream(input);
// Save the bitmap to the file
String path = Environment.getExternalStorageDirectory().toString() + "/polygonattraction/app/";
OutputStream fOut = null;
file = new File(path, "temp.png");
fOut = new FileOutputStream(file);
myBitmap.compress(Bitmap.CompressFormat.PNG, 85, fOut);
fOut.flush();
fOut.close();
}
catch (IOException e) {}
Log.w("tttt", "got bitmap");
Uri uri = Uri.fromFile(file);