Display byte array of jpeg  in jsp

I have a byte array of jpeg image in my jsp. Now I want to display it in my image. I tried but i could not see the image but a red mark image is comming on the screeen
Please help me out. I deadly help need ASAP. Thanks in advance.
this is how i tried
response.setContentType("image/jpeg");
ServletOutputStream os = response.getOutputStream();
// i get byte array from loDocumentDVO.getFileContents():
byte[] fileContent = loDocumentDVO.getFileContents();
os.write(fileContent);
os.flush();

Thank you for your sharp words.
I have now compiled the ImageServlet I have adapted slightly from http://balusc.xs4all.nl/srv/dev-jep-img.html
I am trying to run it with
<html>
<body>
<img src="image?file=plan.jpg" alt="Plan" />
</body>
</html>
but all that is displayed is the word Plan.
My servlet has been compiled and put into webapps\test\classes\example directory.
My web.xml contains
<servlet>
<servlet-name>ImageServlet</servlet-name>
<servlet-class>example.ImageServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ImageServlet</servlet-name>
<url-pattern>/image/*</url-pattern>
</servlet-mapping>
The servlet code is
package example;
import java.io.*;
import java.net.URLConnection;
import javax.servlet.*;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ImageServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response)
          throws ServletException, IOException {
        String imageFilePath = getServletContext().getRealPath("/WEB-INF/images");
        // Get file name from request.
        String imageFileName = request.getParameter("file");
     System.out.println("Path: "+imageFilePath+" Name: "+imageFileName);
        // Check if file name is supplied to the request.
        if (imageFileName != null) {
            // Strip "../" and "..\" (avoid directory sniffing by hackers!).
            imageFileName = imageFileName.replaceAll("\\.+(\\\\|/)", "");
        } else {
            return;
        // Prepare file object.
        File imageFile = new File(imageFilePath, imageFileName);
        // Check if file actually exists in filesystem.
        if (!imageFile.exists()) {
            return;
        // Get content type by filename.
        String contentType = URLConnection.guessContentTypeFromName(imageFileName);
        // Check if file is actually an image (avoid download of other files by hackers!).
        // For all content types, see: http://www.w3schools.com/media/media_mimeref.asp
        if (contentType == null || !contentType.startsWith("image")) {
            return;
        // Prepare streams.
        BufferedInputStream input = null;
        BufferedOutputStream output = null;
        try {
            // Open image file.
            input = new BufferedInputStream(new FileInputStream(imageFile));
            int contentLength = input.available();
            // Init servlet response.
            response.reset();
            response.setContentLength(contentLength);
            response.setContentType(contentType);
            response.setHeader(
                "Content-disposition", "inline; filename=\"" + imageFileName + "\"");
            output = new BufferedOutputStream(response.getOutputStream());
            // Write file contents to response.
            while (contentLength-- > 0) {
                output.write(input.read());
            // Finalize task.
            output.flush();
        } catch (IOException e) {
            // Something went wrong?
            e.printStackTrace();
        } finally {
            // Gently close streams.
            if (input != null) {
                try {
                    input.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    // This is a serious error. Do more than just printing a trace.
            if (output != null) {
                try {
                    output.close();
                } catch (IOException e) {
                    e.printStackTrace();
                    // This is a serious error. Do more than just printing a trace.
}The servlet isn't being called - nothing is output to my server log file. Changing the name of my servlet doesn't change the result.
I can't see why the servlet isn't being called.
I have built another simple servlet that does work so I know my server is OK.
Any suggestions?
Thanks,
David

Similar Messages

  • Displaying Byte Array images in coldfusion

    This has been driving me crazy for a couple of days now.I
    have a Java class that returns pictures stored in a DB as a Byte
    Array.
    I am able to display the image but that is all i am able to
    do - I want to display the image name, description etc in a HTML
    before i display the actual image but i can't seem to find a way to
    do that.
    I tried using CFcontent as well and that did not help
    either.This is what i am currently doing - and all that displays on
    the screen is the picture and all content before the picture is
    nowhere to be seen.
    Picture Name: #variables.picName#
    Picture Description:#variables.picDescription#
    <cfscript>
    context = getPageContext();
    response = context.getResponse().getResponse();
    out = response.getOutputStream();
    response.setContentType("image/jpeg");
    response.setContentLength(arrayLen(session.picture));
    out.write(session.picture);
    out.flush();
    out.close();
    </cfscript>
    Any help will be greatly appreciated.

    Mark,
    Note that the portal sets the content type (e.g, text/html) and encoding
    as the portal page starts rendering. In your case, the
    setContentType() would be useless since the servlet container won't let
    you change it. You can either use a popup browser window for the pdf as
    Kunal suggested, or use an iframe if you want to render the pdf inside
    the portlet window.
    Subbu
    Mark Gilleece wrote:
    Hi,
    i need to display a PDF file. The PDF is stored in a byte array. This works fine when i run my code (see below) from the .jpf via the debugger/browser, but when i use it as a portlet, in the portal, it does not work ?
    Any help is much appreciated.
    Thanks
    Mark
    byte[] pdfDocument = docStore.getPDF();
    ServletOutputStream outPdf = response.getOutputStream();
    response.setContentType("application/pdf");
    outPdf.write(pdfDocument);
    outPdf.flush();
    outPdf.close();

  • Display byte array image or ole object in Section through dynamic code?

    To Start I am a Complete Newbe to Crystal Reports. I have taken over a project originally written in VS2003 asp.net using SQL Server 2005 and older version of Crytal Reports. I have moved project to VS2010 and Cryatal Reports 10 still using SQL Server 2005. Have multiple reports (14 to be exact) that display data currently being pulled from database suing a dataset, each report has from 4 to 14 Sections. I have modified database table with two new fields. Field1 contains string data with full path to a scanned document (pdf or jpeg). Field2 holds a byte array of the actual image of the scanned document. I have tested the database and it does infact contain the byte array and can display the image via VB.net code. I can make the report display the scanned image using ole object.
    Now my real question: I need to add a new Section and it should display either the byte array of the scanned image or the actual scanned image (pdf or jpeg) . How can I have it do either of these options via code dynamicly while application is running?

    First; only CRVS2010 is supported on VS2010. You can download CRVS2010 from here;
    SAP Crystal Reports, developer version for Microsoft Visual Studio: Updates & Runtime Downloads
    Developer Help files are here:
    Report Application Server .NET API Guide http://help.sap.com/businessobject/product_guides/sapCRVS2010/en/xi4_rassdk_net_api_en.zip
    Report Application Server .NET SDK Developer Guide http://help.sap.com/businessobject/product_guides/sapCRVS2010/en/xi4_rassdk_net_dg_en.zip
    SAP Crystal Reports .NET API Guide http://help.sap.com/businessobject/product_guides/sapCRVS2010/en/crnet_api_2010_en.zip
    SAP Crystal Reports .NET SDK Developer Guide http://help.sap.com/businessobject/product_guides/sapCRVS2010/en/crnet_dg_2010_en.zip
    To add the images, you have a number of options re. how to. You even have two SDKs that y ou can use (RAS and CR).
    Perhaps the best place to start is with KB [1296803 - How to add an image to a report using the Crystal Reports .NET InProc RAS SDK|http://www.sdn.sap.com/irj/servlet/prt/portal/prtroot/com.sap.km.cm.docs/oss_notes_boj/sdn_oss_boj_bi/sap(bD1lbiZjPTAwMQ==)/bc/bsp/spn/scn_bosap/notes%7B6163636573733d36393736354636443646363436353344333933393338323636393736354637333631373036453646373436353733354636453735364436323635373233443330333033303331333233393336333833303333%7D.do]. The KB describes how to add images to a report using the InProc RAS SDK, but also references other KBs that use CR SDK.
    Also, don't forget to use the search box in the top right corner of this web page.
    Ludek
    Follow us on Twitter http://twitter.com/SAPCRNetSup
    Got Enhancement ideas? Try the [SAP Idea Place|https://ideas.sap.com/community/products_and_solutions/crystalreports]

  • Displaying byte array

    Hi
    I want to display a byte array. example : data. In servlet&JSP Combination using the following code I can able to display in web browser:
    OutputStream out = response.getOutputStream();
    out.write(data);Is there is any ways to display it in the JSF.
    Thanks

    This is what the console is displaying. But I can view the images.
    [7/13/05 16:11:16:308 CDT] 7f5c44f8 WebGroup E SRVE0026E: [Servlet Error]-[Faces Servlet]: java.lang.IllegalStateException: Cannot forward. Response already committed. (Servlet 2.3, SRV 8.4)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:150)
         at com.ibm.faces.context.MultipartExternalContextImpl.dispatch(MultipartExternalContextImpl.java:320)
         at com.sun.faces.application.ViewHandlerImpl.renderView(ViewHandlerImpl.java:142)
         at com.sun.faces.lifecycle.RenderResponsePhase.execute(RenderResponsePhase.java:87)
         at com.sun.faces.lifecycle.LifecycleImpl.phase(LifecycleImpl.java:200)
         at com.sun.faces.lifecycle.LifecycleImpl.render(LifecycleImpl.java:117)
         at javax.faces.webapp.FacesServlet.service(FacesServlet.java:198)
         at com.ibm.ws.webcontainer.servlet.StrictServletInstance.doService(StrictServletInstance.java:110)
         at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet._service(StrictLifecycleServlet.java:174)
         at com.ibm.ws.webcontainer.servlet.IdleServletState.service(StrictLifecycleServlet.java:313)
         at com.ibm.ws.webcontainer.servlet.StrictLifecycleServlet.service(StrictLifecycleServlet.java:116)
         at com.ibm.ws.webcontainer.servlet.ServletInstance.service(ServletInstance.java:283)
         at com.ibm.ws.webcontainer.servlet.ValidServletReferenceState.dispatch(ValidServletReferenceState.java:42)
         at com.ibm.ws.webcontainer.servlet.ServletInstanceReference.dispatch(ServletInstanceReference.java:40)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.handleWebAppDispatch(WebAppRequestDispatcher.java:983)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.dispatch(WebAppRequestDispatcher.java:564)
         at com.ibm.ws.webcontainer.webapp.WebAppRequestDispatcher.forward(WebAppRequestDispatcher.java:200)
         at com.ibm.ws.webcontainer.srt.WebAppInvoker.doForward(WebAppInvoker.java:119)
         at com.ibm.ws.webcontainer.srt.WebAppInvoker.handleInvocationHook(WebAppInvoker.java:276)
         at com.ibm.ws.webcontainer.cache.invocation.CachedInvocation.handleInvocation(CachedInvocation.java:71)
         at com.ibm.ws.webcontainer.srp.ServletRequestProcessor.dispatchByURI(ServletRequestProcessor.java:182)
         at com.ibm.ws.webcontainer.oselistener.OSEListenerDispatcher.service(OSEListener.java:334)
         at com.ibm.ws.webcontainer.http.HttpConnection.handleRequest(HttpConnection.java:56)
         at com.ibm.ws.http.HttpConnection.readAndHandleRequest(HttpConnection.java:618)
         at com.ibm.ws.http.HttpConnection.run(HttpConnection.java:439)
         at com.ibm.ws.util.ThreadPool$Worker.run(ThreadPool.java:672)
    Thank you,

  • Displaying byte array PDF file in Portal

    Hi,
    i need to display a PDF file. The PDF is stored in a byte array. This works fine when i run my code (see below) from the .jpf via the debugger/browser, but when i use it as a portlet, in the portal, it does not work ?
    Any help is much appreciated.
    Thanks
    Mark
    byte[] pdfDocument = docStore.getPDF();
    ServletOutputStream outPdf = response.getOutputStream();
    response.setContentType("application/pdf");
    outPdf.write(pdfDocument);
    outPdf.flush();
    outPdf.close();

    Mark,
    Note that the portal sets the content type (e.g, text/html) and encoding
    as the portal page starts rendering. In your case, the
    setContentType() would be useless since the servlet container won't let
    you change it. You can either use a popup browser window for the pdf as
    Kunal suggested, or use an iframe if you want to render the pdf inside
    the portlet window.
    Subbu
    Mark Gilleece wrote:
    Hi,
    i need to display a PDF file. The PDF is stored in a byte array. This works fine when i run my code (see below) from the .jpf via the debugger/browser, but when i use it as a portlet, in the portal, it does not work ?
    Any help is much appreciated.
    Thanks
    Mark
    byte[] pdfDocument = docStore.getPDF();
    ServletOutputStream outPdf = response.getOutputStream();
    response.setContentType("application/pdf");
    outPdf.write(pdfDocument);
    outPdf.flush();
    outPdf.close();

  • Display jpeg byte array with JSP !!

    I am new in JSP area so maybe I ask a easy question !!
    First, on the server side:I use a C++ program to stream sequence jpeg data out(FF D8 ~ FF D9).
    Second, on the client side:I use jsp to open a socket and read
    data to a byte array.
    Can anyone tell me how to display the jpeg array on browser one by one ?

    um... like video frames, or just a single image? I wouldn't really use JSP for that, I'd use a servlet, set the content-type to image/jpeg and just write out the bytes. Unless you are talking about displaying the bytes themselves, in which case, a JSP page would be better. If it's video frames, I'm not sure how to have the browser do that, since most no longer support server push.

  • How to load and display a byte array (jpeg) image file dynamically in Flex?

    My web service client (servlet) received a binary jpeg data from an Image Server. The Flex application invokes the
    servlet via HttpService and receives the binary jpeg data as byte array.  How could it be displayed dynamically
    without writing the byte array to a jpeg file?  Please help (some sample code is very much appreciated).

    JPEGEncoder is only useful for converting BitmapData to ByteArray, not the other way around.
    By the way JPEGEncoder and PNGEncoder are part of the Flex SDK now, so no need to use AS3Lib (alltough it's a good library to have around).
    To display/use a ByteArray as image, use a Loader instance with the loadBytes method.
        Loader.loadBytes(bytes:ByteArray, context:LoaderContext = null);
    Listen for the complete event on the Loader.contentLoaderInfo and get the BitmapData in the event handler.
    private function loadJpeg():void {
        var loader:Loader = new Loader();
        loader.contentLoaderInfo.addEventListener(Event.COMPLETE, loaderCompleteHandler);
        //jpgBA is the ByteArray loaded from webservice
        loader.loadBytes(jpgBA);
    private function loaderCompleteHandler(evt:Event):void {
        var t:LoaderInfo = evt.currentTarget as LoaderInfo;
        // display the jpeg in an Image component
        img.source = t.content;
    <mx:Image id="img" scaleContent="false" />

  • Display an object of Image type or Byte Array

    Hi, lets say i got an image stored in the Image format or byte[]. How can i make it display the image on the screen by taking the values in byte array or Image field?

    Thanks rahul,
    The thing is, i am generating a chart in a servlet
    and setting the image in the form of a byte [] to the
    view bean ( which is binded to the jsp, springs
    framework ). The servlet would return the view bean
    to the jsp and in the jsp, i am suppose to print this
    byte array so as to give me the image..
    I hope this makes sense.. pls help me ou!Well letme see if i got tht right or not,
    you are trying to call Your MODEL (Business layer / Spring Container) from a servlet and you are expressing that logic in form of chart (Image) and trying to save it as a byte array in a view bean and you want to print /display that as an image in a jsp (After Servlet fwd / redirect action) which includes other data using a ViewBean.
    If this is the case...
    As the forwaded JSP can include both image and Textual (hypertext too)..we can try a work around hear...Lets dedicate a Servlet which retreives byte [] from a view bean and gives us an image output. hear is an example and this could be a way.
    Prior to that i'm trying to make few assumptions here....
    1).The chart image which we are trying to express would of format JPEG.
    2).we are trying to take help of<img> tag to display the image from the image generating servlet.
    here is my approach....
    ViewBean.java:
    ============
    public class ViewBean implements serializable{
    byte piechart[];
    byte barchart[];
    byte chart3D[];
    public ViewBean(){
    public byte[] getPieChart(){
    return(this.piechart);
    public byte[] getBarChart(){
    return(this.barchart);
    public byte[] get3DChart(){
    return(this.chart3D);
    public void setPieChart(byte piechart[]){
    this.piechart = piechart;
    public void setBarChart(byte barchart[]){
    this.barchart = barchart;
    public void set3DChart(byte chart3D[]){
    this.chart3D = chart3D;
    }ControllerServlet.java:
    =================
    (This could also be an ActionClass(Ref Struts) a Backing Bean(Ref JSF) or anything which stays at the Controller Layer)
    public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException{
    /* There are few different implementations of getting   BeanFactory Resource
    In,the below example i have used XmlBeanFactory Object to create an instance of (Spring) BeanFactory */
    BeanFactory factory =
    new XmlBeanFactory(new FileInputStream("SpringResource.xml"));
    //write a Util Logic in your Implementation class using JFreeChart (or some open source chart library) and express the images by returning a  byte[]
    ChartService chartService =
    (GreetingService) factory.getBean("chartService");
    ViewBean vb = new ViewBean();
    vb.setPieChart(chartService.generatePieChart(request.getParameter("<someparam>"));
    vb.setBarChart(chartService.generateBarChart(request.getParameter("<someparam1>"));
    vb.set3DChart(chartService.generate3DChart(request.getParameter("<someparam2>"));
    chartService = null;
    HttpSession session = request.getSession(false);
    session.setAttribute("ViewBean",vb);
    response.sendRedirect("jsp/DisplayReports.jsp");
    }DisplayReports.jsp :
    ================
    <%@ page language="java" %>
    <html>
    <head>
    <title>reports</title>
    </head>
    <body>
    <h1 align="center">Pie Chart </h1>
    <center><img src="ImageServlet?req=1" /></center>
    <h1 align="center">Bar Chart </h1>
    <center><img src="ImageServlet?req=2" /></center>
    <h1 align="center">3D Chart</h1>
    <center><img src="ImageServlet?req=3" /></center>
    </body>
    </html>ImageServlet.java
    ==============
    public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
           byte buffer[];
            HttpSession session = request.getSession(false);
            ViewBean vb = (ViewBean) session.getAttribute("ViewBean");
            String req = request.getParameter("req");
            if(req.equals("1") == true)       
                buffer = vb.getPieChart();
            else if(req.equals("2") == true)
                 buffer = vb.getBarChart();
            else if(req.equals("3") == true)
                 buffer = vb.get3DChart();
            JPEGImageDecoder decoder = JPEGCodec.createJPEGDecoder(new ByteArrayInputStream(buffer));
            BufferedImage image =decoder.decodeAsBufferedImage() ;
            response.setContentType("image/jpeg");
            // Send back image
            ServletOutputStream sos = response.getOutputStream();
            JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(sos);
            encoder.encode(image);
        }Note: Through ImageServlet is a Servlet i would categorise it under presentation layer rather to be a part of Controller and added to it all this could be easily relaced by a reporting(BI) server like JasperServer,Pentaho,Actuate................
    Hope the stated implementation had given some idea to you....
    However,If you want to further look into similar implementations take a look at
    http://www.swiftchart.com/exampleapp.htm#e5
    which i believe to be a wonderful tutor for such implementations...
    However, there are many simple (Open) solutions to the stated problem.. if you are Using MyFaces along with spring... i would recommend usage of JSF Chart Tag which is very simple to use all it requires need is to write a chart Object generating methos inside our backing bean.
    For further reference have a look at the below links
    http://www.jroller.com/page/cagataycivici?entry=acegi_jsf_components_hit_the
    http://jsf-comp.sourceforge.net/components/chartcreator/index.html
    NOTE:I've tried it personally using MyFaces it was working gr8 but i had a hardtime on deploying my appln on a Portal Server(Liferay).If you find a workaround i'd be glad to know about it.
    & there are many BI Open Source Server Appls that can take care of this work too.(Maintainace wud be a tough ask when we go for this)
    For, the design perspective had i've been ur PM i wud have choose BI Server if it was corporate web appln on which we work on.
    Hope this might be of some help :)
    REGARDS,
    RaHuL

  • Displaying the .png image stored in an byte array

    Hi,
    I have to download an .png image from a server and i have to store it in a byte array and i have to display this byte array in another servlet. I have written the code to get the image from the remote server in a java class. The java class returns the byte array of the image and i have to display that in an servlet.
    If anybody has the code or any refrence to refer please help me..
    Thanks & Regards
    -Sandeep

    I have pasted code for servlet's doGet method which writes image data...
    public void doGet(HttpServletRequest request, HttpServletResponse response)
    throws
    ServletException, IOException
    HttpSession session = request.getSession(); //taking httpsession
    response.setContentType("image/jpeg");
    ServletOutputStream out = response.getOutputStream(); //taking outputstream of response
    if (rtn.getErrorCode() == 0)
    //this will actually write image file data from where it is being called
    //byte array will contain image data, please load your image into below byte array variable
    byte[] b = new byte[100];
    out.write(b);
    out = null; //making null
    session = null; //making null
    In other servlet, write <img> tag and specify its src attribute to the "name of servlet where u have pasted above code" ..
    Regards,
    Nikhil

  • How to display uploaded jpeg in jsp

    hi all,
    i am uploading image(jpeg) using FormFile in ..............
    then i am trying to display into the jsp but its display bytes only...........
    my code is as below
    jsp
    <html:form action="/viewImage.do" method="post"     enctype="multipart/form-data">
         <table cellpadding="0" cellspacing="0" border="0" summary="Image table">
              <tr>
                   <td align="right">Image </td>
                   <td align="left">
                        <html:file property="image" />
                   </td>
              </tr>
              <tr>
                   <td align="center" colspan="2">
                        <html:submit property="saveImage">Upload Image</html:submit>
                   </td>
              </tr>
    </table>
    </html:form>
    ------------------------my action is
    public void disImage(ActionMapping mapping,
                   ActionForm form, HttpServletRequest request,
                   HttpServletResponse response) throws Exception {
              CompanyImageForm companyImageForm = (CompanyImageForm)form;
              FormFile myFile = companyImageForm.getImage();
         String contentType = myFile.getContentType();
         String fileName = myFile.getFileName();
         int fileSize = myFile.getFileSize();
         byte[] fileData = myFile.getFileData();
    InputStream in = new ByteArrayInputStream(fileData);
         BufferedImage image=javax.imageio.ImageIO.read(in);
    response.setContentType(contentType);
    OutputStream sos = response.getOutputStream();
    ImageIO.write(image,"jpeg",sos);
    }

    Well here is an idea for you...
    1).Upload a File.Now this would be associated with an object like FileItem or FormFile whatsoever implementation we are using make sure the View Object we are using for this implementation is Serializable.
    2).Save the View Object (Form Bean) under the scope of session and forward/redirect it to a JSP.
    3).In the redirected/fprward JSP use <img> tag or equivalent framework tag and make sure you refer the src to a dedicated ImageServlet / Backing Bean(FormAction) Action or etc as per URL settings you are using.
    4).Use the logic which my fellow poster Balus has asked you to apply.
    Hope that might give you some idea.
    REGARDS,
    RaHuL

  • Reading a JPEG as a byte array.

    Hello everyone.
    I am developing a project which involves using JPEG images with Java. I would like to use the java.awt.Image class but there's a snag:
    I am reading the file in as a byte array and then need to pass the bytes to an object to be displayed as an image. "why not just read it as a normal JPEG file in the first place?!" I hear you say. Yes, this would be easier but there is a good reason as to why I am reading as a byte array first and this cannot be worked around.
    If anyone has some suggestions I'd very much like to hear them.
    All the best,
    P.M.

    If all you're going to do is display the image, then you can use Toolkit#createImage(byte[] imagedata). That's about as direct as you can get. If you plan on manipulating the images in any way, though, then as above post says ByteArrayInputStream + ImageIO is the way to go.
    "why not just read it as a normal JPEG file in the first place?!" I hear you say. Yes, this would be easier but there is a good reason as to why I am reading as a byte array first and this cannot be worked around.Fun fact: For the ImageIO package, reading from the file is actually faster than reading from an InputStream that references the file's contents as a byte[] array. Specifically, the ImageInputStream implementation that wraps the file is faster then the one that wraps a generic InputStream.

  • Display image from byte array

    Hello Everybody,
    I need to display an image given in a byte array, how can I show this image in a JFrame?
    1. I tryied saving the image in a .jpg file,
         File file1 = new File("Path to my destination image");2. then I use a FileOutputStream to save the image in the path:
            FileOutputStream fos1 = new FileOutputStream(docu);
            fos1.write(ImageInbyteArray);
            fos1.close();3. Once I have the image in a file I'm trying to load it using a JButton, but the JButton doesn't display the image. I think that for some unknown (at least for me ;-) reason the file isn't still available to be used in the ImageIcon, this is my code:
            imgIconDocu = new ImageIcon("Path to my destination image");
            jBtnDocu = new JButton(imgIconDocu);What's wrong here?
    Thanks a lot

    Does the byte array contain a JPEG image? Where did
    you get the contents of the byte array?yes the array contains the JPEG image, I have a database in PostgreSQL, and the images are stored in blob in the database. I have to call a service in the server and in return it gives me the 3 images as byte arrays, that's the reason I only have the byte arrays. so I tryed saving the images as jpeg files in my hard disk to show them, but it appears that they are not available to show them in Swing after saving them. I can only show the images if I close my application and start it again :-(
    I tryed flushing and closing the FileOutputStream after the writting process (fos.write(bytearrayImage);
    fos.flush();
    fos.close();)
    Y also tryed:
    fos.write(bytearrayImage);
    fos.close();
    fos.flush();But it doesn't work either :-(
    What do you recommend me?.
    Thanks a lot,
    Johnny G L

  • Change quality of JPEG byte array

    I have a JPEG file which I read into a byte array in my program, the problem is that I need to change the quality of this image, is it possible? If so, how?

    i think these two links could help you:
    [JAI cookbook|http://www.lac.inpe.br/~rafael.santos/JIPCookbook/6040-howto-compressimages.jsp]
    [java.sun.com|http://java.sun.com/products/java-media/jai/forDevelopers/jai1_0_1guide-unc/Encode.doc.html#51423]

  • Use byte array of PDF to display PDF in IE browser

    I get byte array of PDF as input argument. I need to use byte array to display PDF in IE browser. I am writing code in doGet method of Servlet to accomplish this. However, PDF never gets displayed. I see Acrobat starting, but original PDF never gets displayed in browser.
    I am using code below in doGet of Servlet:
    resp.setContentType("application/pdf");
    resp.setHeader("Expires", "0");
    resp.setHeader("Cache-Control","must-revalidate, post-check=0,
    pre-check=0");
    resp.setHeader("Pragma", "public");
    resp.setHeader("Pragma", "no-cache"); //HTTP 1.0
    resp.setDateHeader("Expires", 0); //prevents caching at the proxy
    server
    resp.setHeader("Cache-Control", "no-cache"); //HTTP 1.1
    resp.setHeader("Cache-Control", "max-age=0");
    resp.setHeader("Content-disposition", "inline; filename=stuff.pdf");
    byte[] inBytes = getBytesOfPDF(...);
    ByteArrayOutputStream outStream = new ByteArrayOutputStream();
    if(inBytes !=null){
    outStream.write(inBytes);
    outStream.flush();
    I added dummy name of PDF (stuff.pdf) for display, as I heard IE requires a file name with .pdf extension for display.
    But I had no luck with the code above.
    Any help with code will be appreciated.
    [email protected]

    Hi
    Am using the same code and i am able to get the PDF out.
              /* Finally writing it into a PDF */
                   response.setContentType("application/pdf");
                   /* filename could be any thing */
                   response.setHeader("Content-Disposition",
                             "attachment; filename=Report.pdf");
                   response.setContentLength(content.length);
                   response.getOutputStream().write(content);
                   response.getOutputStream().flush();
    But this also throws a error in the server :
    java.lang.IllegalStateException: getOutputStream() has already been called for this response
         at org.apache.catalina.connector.Response.getWriter(Response.java:606)
         at org.apache.catalina.connector.ResponseFacade.getWriter(ResponseFacade.java:195)
         at org.springframework.web.servlet.view.freemarker.FreeMarkerView.processTemplate(FreeMarkerView.java:344)
         at org.springframework.web.servlet.view.freemarker.FreeMarkerView.doRender(FreeMarkerView.java:280)
         at org.springframework.web.servlet.view.freemarker.FreeMarkerView.renderMergedTemplateModel(FreeMarkerView.java:225)
         at org.springframework.web.servlet.view.AbstractTemplateView.renderMergedOutputModel(AbstractTemplateView.java:174)
         at org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:239)
         at org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1142)
         at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:879)
         at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:792)
         at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:476)
         at org.springframework.web.servlet.FrameworkServlet.doPost(FrameworkServlet.java:441)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:709)
         at javax.servlet.http.HttpServlet.service(HttpServlet.java:802)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:252)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
         at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:672)
         at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:463)
         at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:398)
         at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:301)
         at org.ca.ielts.presentationtier.servlet.AuthorisationAuthenticationFilter.doFilter(Unknown Source)
         at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:202)
         at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:173)
         at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:213)
         at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:178)
         at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:126)
         at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:105)
         at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:107)
         at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:148)
         at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:868)
         at org.apache.coyote.http11.Http11BaseProtocol$Http11ConnectionHandler.processConnection(Http11BaseProtocol.java:663)
         at org.apache.tomcat.util.net.PoolTcpEndpoint.processSocket(PoolTcpEndpoint.java:527)
         at org.apache.tomcat.util.net.LeaderFollowerWorkerThread.runIt(LeaderFollowerWorkerThread.java:80)
         at org.apache.tomcat.util.threads.ThreadPool$ControlRunnable.run(ThreadPool.java:684)
         at java.lang.Thread.run(Thread.java:595)
    Any Clues how this has to be fixed.????

  • How to save Byte Array of raw data into JPEG image.

    Hello!
    I have a image and I stored its data as byte array as
    bimage = bitmap1.getRawData();
    now I have Byte[] bimage, I want to save it as .jpeg image.
    and show that image..............

    the short way is this:
    ImageIO.write(bimage, "jpeg", new File("image.jpg"));
    Where you use the original Image object... but it has to be a java.awt.image.RenderedImage (which a java.awt.image.BufferedImage is). So this method would come in handy.
         public static BufferedImage getBufferedImage(Image img) {
              // if the image is already a BufferedImage, cast and return it
              if((img instanceof BufferedImage) && background == null) {
                   return (BufferedImage)img;
              // otherwise, create a new BufferedImage and draw the original
              // image on it
              int w = img.getWidth(null);
              int h = img.getHeight(null);
              BufferedImage bi = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
              Graphics2D g2d = bi.createGraphics();
              g2d.drawImage(img, 0, 0, w, h, null);
              g2d.dispose();
              return bi;
         }If the byte array you have is raw image data, then you can look at the javax.imageio package and see what you can do with those classes.

Maybe you are looking for