Add an Image in an iText PDF document in Android Studio - java

I am trying to add an image in my iText PDF document in Android Studio, with Java, but it always shows the error NullPointerException.
The codes i've trying are:
1.
try {
InputStream inputStream = context.getAssets().open("res/drawable/logo.png");
Bitmap bitmapA = BitmapFactory.decodeStream(inputStream);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmapA.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image image = Image.getInstance(stream.toByteArray());
return image;
}catch (Exception e){
e.printStackTrace();
}
2.
try {
Drawable d = context.getResources().getDrawable(R.drawable.logo);
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());
return image;
}catch (Exception e){
e.printStackTrace();
}
3.
try {
Drawable d = context.getDrawable(R.drawable.logo);
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());
return image;
}catch (Exception e){
e.printStackTrace();
}
4.
try {
Image image = Image.getInstance("res/drawable/logo.png");
return image;
} catch (BadElementException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
..and no one of those codes are working. Always the same error, not founding the resource.
My question is, can I add an image to an iText doc? How can I do this?
Ps. I'm using iText5 (implementation 'com.itextpdf:itextg:5.5.10').

I solved my problem with some small changes. I'll let it here if anyone else is needing it.
Bitmap bm = BitmapFactory.decodeResource(getResources(), R.drawable.logo);
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bm.compress(Bitmap.CompressFormat.PNG, 100, stream);
Image img = null;
byte[] byteArray = stream.toByteArray();
try {
img = Image.getInstance(byteArray);
} catch (BadElementException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Then, this img you can add to your PDF file in iText.

Related

App crashed when sending images through TCP

I'm creating a simple stream to send images taken from client's screen from client to server. For now I can receive the first image but then the app crashed unexpectedly. The idea is send the size and the image in byte array, the server receive that byte array and convert to image.
FromClient:
public void run() {
image = new BufferedImage(NORM_PRIORITY, MIN_PRIORITY, MAX_PRIORITY);
while(continueLoop) {
//send captured screen
image = robot.createScreenCapture(rectangle);
try {
//Initiate the stream
OutputStream out = clientSocket.getOutputStream();
DataOutputStream dos = new DataOutputStream(out);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(image, "jpg", baos);
// store the size of each image
byte[] size = ByteBuffer.allocate(4).putInt(baos.size()).array();
dos.write(size);
dos.write(baos.toByteArray(), 0, baos.toByteArray().length);
dos.flush();
} catch(IOException e) {
e.printStackTrace();
e.printStackTrace();
continueLoop = false;
}
try {
Thread.sleep(30);
} catch(InterruptedException e) {
e.printStackTrace();
System.out.println(e.getMessage());
}
}
}
ToServer:
public void run() {
boolean continueLoop = true;
try {
drawGUI();
// Initiate the stream
InputStream is = clientSocket.getInputStream();
DataInputStream configGraphicStream = new DataInputStream(is);
BufferedImage image = null;
while(continueLoop) {
//receive the size of image and convert to type int
byte[] sizeInByte = new byte[64];
configGraphicStream.read(sizeInByte);
int length = ByteBuffer.wrap(sizeInByte).asIntBuffer().get();
try {
// Get images
byte[] img = new byte[length];
configGraphicStream.readFully(img, 0, img.length);
image = ImageIO.read(new ByteArrayInputStream(img));
}
catch (Exception e) {
System.out.println(e.getMessage());
}
//draw images
if( image != null)
{
Graphics graphics = clientPanel.getGraphics();
graphics.drawImage(image, 0, 0, clientPanel.getWidth(), clientPanel.getHeight(), clientPanel);
}
System.out.println("Receiving image");
Thread.sleep(30);
}
} catch (Exception e) {
e.printStackTrace();
}
}
Please help me solve this problem.

Android render pdf to bitmap with itext library

I am trying to convert a pdf stored in my assets folder into bitmap using PdfViewer.jar.
This is my code:
public static Bitmap renderToBitmap(InputStream inStream) {
Bitmap bitmap = null;
try {
byte[] bArray = IOUtils.toByteArray(inStream);
ByteBuffer buf = ByteBuffer.wrap(bArray);
PDFPage mPdfPage = new PDFFile(buf).getPage(0, true);
float width = mPdfPage.getWidth();
float height = mPdfPage.getHeight();
bitmap = mPdfPage.getImage((int) (width), (int) (height), null);
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
inStream.close();
} catch (IOException e) {
// do nothing because the stream has already been closed
}
}
return bitmap;
}
This code is doing what I need. But the resulting bitmap quality is very poor.
How can I increase the quality of bitmap created ?

Receiving multiple byte arrays from socket

I'm currently working on a remote desktop app. The server part runs on Android device and the client one on PC/Raspberry PI. I've encountered a problem with receiving my bitmaps (screenshots from Android, send as byte arrays).
The Android Server code goes like this:
//os = new ObjectOutputStream(s.getOutputStream());
public void run() {
while(true){
try {
View v1 = getWindow().getDecorView().getRootView();
v1.setDrawingCacheEnabled(true);
Bitmap bitmap = Bitmap.createBitmap(v1.getDrawingCache());
v1.setDrawingCacheEnabled(false);
int quality = 100;
ByteArrayOutputStream stream = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.JPEG, quality, stream);
byte[] byteArray = stream.toByteArray();
if(byteArray.length>0) {
os.writeInt(byteArray.length);
os.write(byteArray, 0, byteArray.length);
os.flush();
}
} catch (IOException e) {
e.printStackTrace();
}}}
And the Receiver App on PC like this:
//ois = new ObjectInputStream(s.getInputStream());
public void run() {
while(true){
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
int size = ois.readInt();
System.out.println(size);
byte[] data = new byte[size];
int length = 0;
while ((length = ois.read(data,0,size)) != -1) {
out.write(data, 0, size);
out.flush();
}
byte[] bytePicture = out.toByteArray();
out.close();
BufferedImage buffImage = byteArrayToImage(bytePicture);
ImageIcon imgIcon = new ImageIcon(buffImage);
l.setIcon(imgIcon);
} catch (IOException e) {
}}}
byteArrayToImage
public static BufferedImage byteArrayToImage(byte[] bytes) {
BufferedImage bufferedImage = null;
try {
InputStream inputStream = new ByteArrayInputStream(bytes);
bufferedImage = ImageIO.read(inputStream);
} catch (IOException ex) {
System.out.println(ex.getMessage());
}
return bufferedImage;
}
The problem is that in the receiver app I get Java OutOfMemoryException because I cannot differ between incoming screenshots. I really cannot figure out how to read exactly the size of a bitmap (as byte array) then display it and read another and another one. Any help will be appreciated. Thanks in advance.

How to compress tiff image

I am currently storing the tiff image in BufferredImage during runtime and displaying the same in image src tag of hmtl.
My tiff image size is about 60kb and currently it takes approx 1 sec time to load in web browser.
Is there any way to compress the tiff image or BufferedImage so that the time to load the image in browser can be faster.
Below is my code for saving tiff image in BufferredImage.
public BufferedImage savetiff(File srcFilePath) throws IOException {
FileSeekableStream stream = new FileSeekableStream(srcFilePath);
TIFFDecodeParam decodeParam = new TIFFDecodeParam();
decodeParam.setDecodePaletteAsShorts(true);
ParameterBlock params = new ParameterBlock();
params.add(stream);
RenderedOp image1 = JAI.create("tiff", params);
BufferedImage img = image1.getAsBufferedImage();
return img;
}
Code for converting tiff to image but in this code I have to save the jpeg image in disk and then I have to read it again. If there is any way to convert tiff to JPEG and save in BufferedImage.
public boolean tiff2JPG(File srcFilePath, File destFilePath) {
boolean status = false;
SeekableStream s = null;
RenderedImage op = null;
ImageDecoder dec = null;
TIFFDecodeParam param = null;
FileOutputStream fos = null;
JPEGEncodeParam jpgparam = null;
ImageEncoder en = null;
try {
s = new FileSeekableStream(srcFilePath);
dec = ImageCodec.createImageDecoder("tiff", s, param);
op = dec.decodeAsRenderedImage(0);
fos = new FileOutputStream(destFilePath);
jpgparam = new JPEGEncodeParam();
jpgparam.setQuality(67);
en = ImageCodec.createImageEncoder("jpeg", fos, jpgparam);
en.encode(op);
status = true;
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
fos.flush();
fos.close();
} catch (IOException io) {
// TODO Auto-generated catch block
io.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
return status;
Please advice.
Regards,
Dinesh Pise

jpegs are corrupted when resampled with java imageIO

The JPEG Images that ImageIO generated view correctly on windows file explorer, as well as safari webbrowser, but in FireFox, the resampled images are clipped.
How do I use ImageIO without corrupting the resamples?
The code should resize image keeping aspect ratio, as well as do jpeg compression, the convert it to a byte [] array, which could be written to a socket.
some of my code. in this snippet, I tried adding Jui library, but still the same issue.
public static BufferedImage imageistream;
public void Resample(String child,double width,double height) throws Exception, InvalidFileStructureException, InvalidImageIndexException, UnsupportedTypeException, MissingParameterException, WrongParameterException
{
String imagePath = "";
if(this.is_mac_unix == true)
{
imagePath = this.path+"/"+child;
}
else
{
imagePath = this.path+"\\"+child;
}
PixelImage bmp = null;
try {
bmp = ToolkitLoader.loadViaToolkitOrCodecs(imagePath, true, null);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Resample resample = new Resample();
resample.setInputImage(bmp);
double fixedRatio = width/height;
if(((double)bmp.getWidth()/bmp.getHeight()) >= fixedRatio)
{
resample.setSize((int)width,(int)(bmp.getHeight()/(bmp.getWidth()/width)));
}
else
{
resample.setSize((int)width,(int)(bmp.getWidth()/(bmp.getHeight()/height)));
}
resample.setFilter(Resample.FILTER_TYPE_LANCZOS3);
resample.process();
PixelImage scaledImage = resample.getOutputImage();
Processor.imageistream = ImageCreator.convertToAwtBufferedImage(scaledImage);
bmp = null;
Runtime rt = Runtime.getRuntime();
rt.gc();
}
...
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(Processor.imageistream, "jpg", baos);
// ImageIO.write(Processor.imageistream, "png", baos); Works!
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
byte bytes[] = baos.toByteArray();
ByteArrayInputStream is = new ByteArrayInputStream(bytes);
OutputStream os = (OutputStream)obj[1];
OutputStreamWriter writer = (OutputStreamWriter)obj[0];
byte[] buf= new byte[4096];
int c;
try {
while (true) {
c= is.read(buf);
if (c<= 0) break;
os.write(buf, 0, c);
}
writer.close();
os.close();
is.close();
I've been successfully using:
BufferedImage bufferedImage = ImageIO.read(..);
Image img = bufferedImage.getScaledInstance(..);
BufferedImage result = // transform Image to BufferedImage
ImageIO.write(result, "image/jpeg", response.getOutputStream());
transformation is simply writing the contents of the image to a new BufferedImage

Categories