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
Related
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.
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.
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 ?
I am trying to create a document with htmlWriter in com.lowagie.text in Java.
What I do, is that I create an image (from qr-code) and try to add it to the document.
The document is connected to an ByteArrayOutputStream, and then I write it out to a ServletOutputStream.
When I create an image from bitmatrix, nothing happens.
I wonder if this is because the html need an image-URL. So If I get the image from url, it shows. But when I just create an image in java, it will not display this in the html?!?
Can anyone help me?
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// setting some response headers
response.setHeader("Expires", EXPIRES);
// setting the content type
response.setContentType(CONTENT_TYPE);
ServletOutputStream out = null;
ByteArrayOutputStream baos = null;
try {
baos = getHtmlTicket();
// write ByteArrayOutputStream to the ServletOutputStream
out = response.getOutputStream();
baos.writeTo(out);
}
catch (Exception e) {
log.error(e.getMessage(), e);
response.setContentType("text/html");
// response.setHeader("Content-Disposition", "filename=\"" + filename + "\"");
response.getWriter().write("<p>Det har oppst�tt en feil!</p>");
response.getWriter().write("<p>" + new Date().toString() + "</p>");
response.getWriter().write("<!-- " + e.getMessage() + " -->");
response.flushBuffer();
}
public ByteArrayOutputStream getHtmlTicket() {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document document = new Document();
String myCodeText = "YO YOU";
int size = 128;
try {
HtmlWriter.getInstance(document, baos);
document.open();
document.add(new Paragraph("Hello World"));
document.add(new Paragraph(new Date().toString()));
Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<EncodeHintType, ErrorCorrectionLevel>();
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix byteMatrix = qrCodeWriter.encode(myCodeText,BarcodeFormat.QR_CODE, size, size, hintMap);
int pictureWidth = byteMatrix.getWidth();
BufferedImage bimage = new BufferedImage(pictureWidth, pictureWidth,
BufferedImage.TYPE_INT_RGB);
bimage.createGraphics();
Graphics2D graphics = (Graphics2D) bimage.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, pictureWidth, pictureWidth);
graphics.setColor(Color.BLACK);
for (int i = 0; i < pictureWidth; i++) {
for (int j = 0; j < pictureWidth; j++) {
if (byteMatrix.get(i, j)) {
graphics.fillRect(i, j, 1, 1);
}
}
}
com.lowagie.text.Image image = com.lowagie.text.Image.getInstance(bimage , null);
document.add(image);
}
catch (DocumentException e) {
e.printStackTrace();
} catch (MalformedURLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
catch (WriterException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
document.close();
return baos;
}
HtmlWriter was created to test the Itext library during development. That is why the image only display as a square without content. That is also why the creators of Itext have removed htmlWriter it in later versions.
If you want the response to display the image (must be bufferedImage) in HTML, you can do so by converting the image to Base64 like this:
private String addImageToHTML(BufferedImage bf) {
String base64String = "";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
try {
ImageIO.write(bf, "png", baos);
base64String = DatatypeConverter.printBase64Binary(baos.toByteArray());
}
catch (IOException e) {
e.printStackTrace();
}
return "<img style='max-width:100%' src='data:image/png;base64,"+ base64String + "' alt='IMG DESC'/>";
}
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