0

AImage from binary file

asked 2011-06-30 03:09:59 +0800

Neus gravatar image Neus
1415 14

Hi,
I'm getting an image from a data base and I want to show this image with zk's image component.
I'm getting a String that represents the image so I thought to do something like this:

String fichero = imagenbin.getFichero(); //the String that represents the image
AImage aimagen;
	try {
		aimagen = new AImage("",fichero.getBytes());
		img.setContent(aimagen);
	} catch (IOException e) {
		// TODO Auto-generated catch block
		e.printStackTrace();
	}

But I get several exceptions
This:
java.io.IOException: Unknown image format: 
	at org.zkoss.image.AImage.init(AImage.java:125)
	at org.zkoss.image.AImage.<init>(AImage.java:73)
	at org.sts.PruebaImagenbin.PruebaImagenbin.onCreate$img(PruebaImagenbin.java:72)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at org.zkoss.zk.ui.event.GenericEventListener.onEvent(GenericEventListener.java:87)
	at org.zkoss.zk.ui.impl.EventProcessor.process0(EventProcessor.java:192)
	at org.zkoss.zk.ui.impl.EventProcessor.process(EventProcessor.java:138)
	at org.zkoss.zk.ui.impl.EventProcessingThreadImpl.process0(EventProcessingThreadImpl.java:517)
	at org.zkoss.zk.ui.impl.EventProcessingThreadImpl.sendEvent(EventProcessingThreadImpl.java:121)
	at org.zkoss.zk.ui.event.Events.sendEvent(Events.java:319)
	at org.zkoss.zk.ui.event.Events.sendEvent(Events.java:329)
	at org.zkoss.zk.ui.AbstractComponent$ForwardListener.onEvent(AbstractComponent.java:3042)
	at org.zkoss.zk.ui.impl.EventProcessor.process0(EventProcessor.java:192)
	at org.zkoss.zk.ui.impl.EventProcessor.process(EventProcessor.java:138)
	at org.zkoss.zk.ui.impl.EventProcessingThreadImpl.process0(EventProcessingThreadImpl.java:517)
	at org.zkoss.zk.ui.impl.EventProcessingThreadImpl.run(EventProcessingThreadImpl.java:444)

or sometimes I get this:

sun.awt.image.ImageFormatException: Bogus marker length
	at sun.awt.image.JPEGImageDecoder.readImage(Native Method)
	at sun.awt.image.JPEGImageDecoder.produceImage(Unknown Source)
	at sun.awt.image.InputStreamImageSource.doFetch(Unknown Source)
	at sun.awt.image.ImageFetcher.fetchloop(Unknown Source)
	at sun.awt.image.ImageFetcher.run(Unknown Source)

Can anyone tell me what I'm doing wrong?

Thank you in advance!

delete flag offensive retag edit

12 Replies

Sort by » oldest newest

answered 2011-06-30 03:23:29 +0800

dennis gravatar image dennis
3669 1 6
http://www.javaworld.com....

Just like the exception said, 1. unknow image format and 2. image format error.
where the image from? a arbitrarily file that been uploaded by an user?
you should add some log in catch code block, dump byte array to a file to see what is happening.

link publish delete flag offensive edit

answered 2011-06-30 03:38:58 +0800

Neus gravatar image Neus
1415 14

Is something I have to put in the first parameter of the constructor of AImage

 aimagen = new AImage("",fichero.getBytes());
?
Becuse everytime I change it the java.io.IOException: Unknown image format: changes and shows this parameter

link publish delete flag offensive edit

answered 2011-06-30 03:41:11 +0800

Neus gravatar image Neus
1415 14

Doing fichero.getBytes() is sufficient to construct the AImage?
fichero is something like "Äþ ¢àEÅÓùZ!1çïÍÇóû?÷?ó)|ûó°ÉV?²" (and much more)

link publish delete flag offensive edit

answered 2011-06-30 05:19:16 +0800

Neus gravatar image Neus
1415 14

updated 2011-06-30 05:19:45 +0800

I'm trying to simulate it with a image from my pc (so I know it is a valid image)

File file = new File("C://AceptarNuevo.png");
int ch;
StringBuffer strContent = new StringBuffer("");
FileInputStream fin = null;
String fichero = "";
try{
	fin = new FileInputStream(file);
	 while( (ch = fin.read()) != -1)
		 strContent.append((char)ch);
	 
	 fin.close();
}catch(FileNotFoundException e){
	System.out.println("El fichero " + file.getAbsolutePath() + " no se encuentra en el sistema");
}catch(IOException ioe){
		System.out.println("Exception leyendo el fichero" + ioe);
}
fichero = strContent.toString(); //I do this to simulate the String I recive from DB
AImage aimagen = null;
try {
	aimagen = new AImage("",fichero.getBytes());
	img.setContent(aimagen);
} catch (IOException e) {
	System.err.println(e.getCause());
	// TODO Auto-generated catch block
	e.printStackTrace();
}

With this code I get the java.io.Exception that I described above

link publish delete flag offensive edit

answered 2011-06-30 05:35:49 +0800

dennis gravatar image dennis
3669 1 6
http://www.javaworld.com....

Neus,
Byte and Char/String are different, do you know that?
It is no possible to write a image byte array to a string and expecting to get a return byte array from that string is correct.

How do you store image byte data to the db? maybe you should look into that also please.

link publish delete flag offensive edit

answered 2011-06-30 08:20:50 +0800

marcelodecampos gravatar image marcelodecampos
183

Hi,

Here are some fragments of code to handle image from byte array, as long as image is ok!

    protected BufferedImage currentImage;
    protected Image pgcImage; // Zk image component


    /*
     * LOAD image from any byte array. In this case I use an EJB from database with a blob field.
    */
    protected void loadImage( byte[] object ) throws IOException
    {
        ByteArrayInputStream is = new ByteArrayInputStream( object );
        currentImage = ImageIO.read( is );
    }

    protected void showImage() throws IOException
    {
        int w = currentImage.getWidth();
        int h = currentImage.getHeight();

        if ( imageRateSize == 0.0F ) {
            sizeToFit();
        }
        if ( imageRateSize != 1.0F ) {
            w *= imageRateSize;
            h *= imageRateSize;
            BufferedImage bufferedImage = resizeTrick( currentImage, w, h );
            pgcImage.setContent( bufferedImage ); // THIS IS THE ONLY LINE THAT MATTERS, all the rest is just to resize the image
        }
        else {
            pgcImage.setContent( currentImage );
        }
    }

    private static BufferedImage resizeTrick( BufferedImage image, int width, int height )
    {
        image = createCompatibleImage( image );
        //image = blurImage( image );
        image = resize( image, width, height );
        return image;
    }

    private static BufferedImage createCompatibleImage( BufferedImage image )
    {
        GraphicsConfiguration gc = BufferedImageGraphicsConfig.getConfig( image );
        int w = image.getWidth();
        int h = image.getHeight();
        BufferedImage result = gc.createCompatibleImage( w, h, Transparency.TRANSLUCENT );
        Graphics2D g2 = result.createGraphics();
        g2.drawRenderedImage( image, null );
        g2.dispose();
        return result;
    }

    private static BufferedImage resize( BufferedImage image, int width, int height )
    {
        int type = image.getType() == 0 ? BufferedImage.TYPE_INT_ARGB : image.getType();
        BufferedImage resizedImage = new BufferedImage( width, height, type );
        Graphics2D g = resizedImage.createGraphics();
        g.setComposite( AlphaComposite.Src );

        g.setRenderingHint( RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR );

        g.setRenderingHint( RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY );

        g.setRenderingHint( RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON );

        g.drawImage( image, 0, 0, width, height, null );
        g.dispose();
        return resizedImage;
    }

    protected void sizeToFit()
    {
        if ( currentImage.getWidth() > targetWidth ) {
            imageRateSize = ( ( float )targetWidth ) / ( ( float )currentImage.getWidth() );
        }
        else
            imageRateSize = 1.0F;
    }

I really hope that this may help you!

link publish delete flag offensive edit

answered 2011-06-30 15:53:11 +0800

terrytornado gravatar image terrytornado flag of Germany
9393 3 7 16
http://www.oxitec.de/

Thanks for sharing the code.

link publish delete flag offensive edit

answered 2011-07-01 01:13:09 +0800

Neus gravatar image Neus
1415 14

Thank you very much marcelo!
I will see what I'll do because I don't use blobs and what I'm reciving from DB is a String

link publish delete flag offensive edit

answered 2011-07-01 01:35:03 +0800

dennis gravatar image dennis
3669 1 6
http://www.javaworld.com....

to transfer byte and string , I will use base64 encoding, but blob is the best efficient.

link publish delete flag offensive edit

answered 2011-07-14 05:44:44 +0800

Neus gravatar image Neus
1415 14

I am using base64 encoding now and seems it works OK.
Now I have a problem setting content to iframe
My code is this :
zul

<?page title="new page title" contentType="text/html;charset=UTF-8"?>
<zk>
<window title="new page title" vflex="1" border="normal" apply="org.sts.PruebaImagenbin.PruebaImagenbin">
	<button id="btnSubirDoc" label="Subir documento" upload="true,maxsize=-1,native"/>
	<button id="btnRecuperarDoc" label="Recuperar documento"/>
	<iframe id="doc" hflex="1" vflex="1" />
</window>
</zk>

java class
public void onUpload$btnSubirDoc(Event event){
	ForwardEvent fevent = (ForwardEvent) event;
		Media media = ((UploadEvent)fevent.getOrigin()).getMedia();
		byte[] bytes = media.getByteData();
		char[] encoded = Base64Coder.encode(bytes);
		printme = new String(encoded);
		formato = media.getFormat();
		
	}
	public void onClick$btnRecuperarDoc(Event event){
		AMedia amedia;
		amedia = new AMedia("PRUEBA", formato, null, Base64Coder.decode(printme.toCharArray()));
		doc.setContent(amedia);
}

It works fine except in some cases.
I tried this with 3 pdf. One of them works OK but the other two doesn't appear in the iframe. I try to upload them with Iframe demo (http://www.zkoss.org/zkdemo/composite/iframe?search=iframe) and when select them to upload a message appears saying that these files exceed the maximum size.

I have another problem with word documents. I tried some of them and work OK but with one of them when I try to show it in the iframe microsoft word opens an this error message appears:

Cannot start the converter mswrd632.wpc

I try to upload this file in the Iframe demo and again the max size message appear

Don't know if iframe has a maxsize for files showed or if I'm missing something...

Can anyone help me?
Thank you!

link publish delete flag offensive edit
Your reply
Please start posting your answer anonymously - your answer will be saved within the current session and published after you log in or create a new account. Please try to give a substantial answer, for discussions, please use comments and please do remember to vote (after you log in)!

[hide preview]

Question tools

Follow

RSS

Stats

Asked: 2011-06-30 03:09:59 +0800

Seen: 1,146 times

Last updated: Jul 14 '11

Support Options
  • Email Support
  • Training
  • Consulting
  • Outsourcing
Learn More