Image Conversion with Byte Arrays

I'm trying to read in a byte[] for JPG, PNG, BMP, and GIF files which will then be converted to a .TIFF file so it can be printed on Post Script printers.
Technically I have it working BUT the catch is that it physically needs to create the file. I'd like to have it all done in memmory and not have to actaully have a physical file created.
I have been trying many different things with the JAI.create function. Near as I can see so far that only creates a RenderedImage which then creats a file even if I use "stream" inscreat off "filename".
Any suggestions would be appreciated.
Thanks.

I got it figured out. It does make the TIFF a little bit larger but that's ok.
RenderedOp src = JAI.create("stream", new com.sun.media.jai.codec.ByteArraySeekableStream(image));
ByteArrayOutputStream out = new ByteArrayOutputStream();
JAI.create("encode", src, out, "TIFF", null);
return out.toByteArray();

Similar Messages

  • How to convert a Image object to byte Array?

    Who can tell me, how to convert Image object to byte Array?
    Example:
    public byte[] convertImage(Image img) {
    byte[] b = new byte...........
    return b;

    Hello,
    any way would suit me, I just need a way to convert Image or BufferedImage to a byte[], so that I can save them. Actually I need to save both jpg and gif files without using any 3rd party classes. Please help me out.
    thanx and best wishes

  • 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

  • How to convert an Image to a byte array?

    I want to make a screenshot and then convert the image to a byte of arrays so I can send it through a BufferedOutputStream.
    try
                   robot = new Robot();
                   screenshot = robot.createScreenCapture(new Rectangle(500,500));
                   imageFile = new File("image.png");
                   ImageInputStream iis = ImageIO.createImageInputStream(screenshot);
                   byte[] data = new byte[1024];
                   byte[] tmp = new byte[0];
                   byte[] myArrayImage = new byte[0];
                   int len = 0;
                   int total = 0;
                   while((len = iis.read(data)) != -1 ) // LINE 52 --- EXCEPTION CATCHED HERE
                        total += len;
                        tmp = myArrayImage;
                        myArrayImage = new byte[total];
                        System.arraycopy(tmp,0,myArrayImage,0,tmp.length);
                        System.arraycopy(data,0,myArrayImage,tmp.length,len);
                   ios.close();I get this exception while running:
    Exception in thread "Thread-0" java.lang.NullPointerException
    at Server.run(Server.java:52)
    at java.lang.Thread.run(Unknown Source)

    Fixed that. I got a new problem.
    When I connect to my simple server application that reads the image file, converts it to an array of bytes and sends it back, the file is created on the client side and it containts data, but I am not able to open the image. I have checked that the image that the server is sending is working. So where is the problem?
    The client application recieves the image as following:
    public void run()
            try
                socket = new Socket("127.0.0.1", 2000);
                BufferedOutputStream out_file = new BufferedOutputStream(new FileOutputStream("recieved_img.png"));
                BufferedReader in = new BufferedReader(new InputStreamReader(socket.getInputStream()));
                int inputLine;
                while((inputLine = in.read()) != -1)
                    char c = (char)inputLine;
                    System.out.println(c);
                    out_file.write(inputLine);
            catch(IOException err){ err.printStackTrace(); }
        }And the server sends the image like this;
    try
              socket = server.accept();
              in=new BufferedReader(new InputStreamReader(socket.getInputStream()));
              out = new BufferedOutputStream(socket.getOutputStream());
              out.write(25);
              while((inputLine = in.readLine()) != null)
                   System.out.println(myArrayImage.length);
              System.out.println(inputLine);
                        out.write(myArrayImage);     // Send the array of bytes
         }

  • Converting Image.jpg to byte array

    Hi,
    How do i convert a image (in any format like .jpeg, .bmp, gif) into a byte array
    And also vice versa, converting byte array to image format
    Thank you

    how about Class.getResourceAsStream(String name).read(byte[] b)?

  • Repost: Problem with byte array

    i wrote the following code:
    public class Test {
    byte [] ba = new byte[10];
    void print(String s) { System.out.println(s); }
    void printInitialValues() {
    for (int i=0; i<10; i++)
    ba = (byte)0;
    //System.arraycopy("asdf".getBytes(), 0, ba, 0, 4);*/
    print("byte array " + ba);
    public static void main(String[] args) {
    Test iv = new Test();
    iv.printInitialValues();
    }why the output isn't the string of the serial '0', instead, it seems the random output.
    when i put the line "System...." to the code, the result is the same.
    Can anybody tell me why?
    Regards,
    Jason

    Your byte[] is an object of the type Array. Array does
    not override toString(), and thus you get the default
    Object.toString() behavior. If you want to print out
    the array elements, you'll need to iterate through the
    array manually.And in 1.5 you can use this:
    Arrays.toString(byteArray);/Kaj

  • Problem with byte array

    i wrote the following code:
    public class Test {
    byte [] ba = new byte[10];
    void print(String s) { System.out.println(s); }
    void printInitialValues() {
    for (int i=0; i<10; i++)
    ba[i] = (byte)0;
    //System.arraycopy("asdf".getBytes(), 0, ba, 0, 4);*/
    print("byte array " + ba);
    public static void main(String[] args) {
    Test iv = new Test();
    iv.printInitialValues();
    why the output isn't the string of serial '0', instead, it seems the random output.
    when i put the line "System...." to the code, the result is the same.
    Anybody can tell me why?
    Regards,
    Jason

    Continued [url http://forum.java.sun.com/thread.jsp?forum=31&thread=551032&tstart=0&trange=15]here.

  • Problem with byte array arguments in webservice method call

    I am using JWSDP 1.5 to generate client stubs for a webservice hosted on a Windows 2000 platform.
    One of the methods of the webservice contains a byte array argument. When our application calls this method passing the contents of a TIFF file as the byte array, the method is failing. I have discovered that tthe reason for the failure is that the byte array in the SOAP message has been truncated and is missing its terminating tag.
    Is this a known problem in JWSDP 1.5? Is there a fix for it? Does JWSDP 1.6 resolve this problem?
    Any assistance will be much appreciated.
    Regards,
    Leo

    I'd like to add the the webservice being invoked by the generated client stubs is rpc/encoded.

  • Setting attributes of image stored in byte array in servlet

    Hi,
    I am using a servlet to stream image (GIF) to the browser.
    Image is accessed by browser using the img tag. src attribute points to the servlet which send the image stream.
    Servlet has the image as the array of bytes. It simply write these bytes on the response object's output stream. It does not use any encoder.
    I get the image on the browser. But when I try to see the properties of the image I don't see the type of image. I also don't see the created time, modified time and size of the image. When I do Save As on this image it tries to save it as BMP instead of GIF. Also when I do the print preview I don't see the image in the preview window. When I try to print the web page, it prints everything except this image. I get small cross(image missing) on the printed page.
    I would like to know why the image attributes on browser go missing and why can't I print the image?
    I would like to add that I am getting the image as the array of bytes from a different application on which I do not have control.
    Thanks.

    Hi,
    I am using a servlet to stream image (GIF) to the browser.
    Image is accessed by browser using the img tag. src attribute points to the servlet which send the image stream.
    Servlet has the image as the array of bytes. It simply write these bytes on the response object's output stream. It does not use any encoder.
    I get the image on the browser. But when I try to see the properties of the image I don't see the type of image. I also don't see the created time, modified time and size of the image. When I do Save As on this image it tries to save it as BMP instead of GIF. Also when I do the print preview I don't see the image in the preview window. When I try to print the web page, it prints everything except this image. I get small cross(image missing) on the printed page.
    I would like to know why the image attributes on browser go missing and why can't I print the image?
    I would like to add that I am getting the image as the array of bytes from a different application on which I do not have control.
    Thanks.

  • Deriving color space of an image from a byte array input stream.

    I was wondering, is it possible to derive the color space of an image, i.e. RGB, YCC, GRAY by calculating its bytes?

    Calculate bytes just means doing operations on the
    byte values. That's how I got the height and width of
    the image. Now, I'm wondering if it is possible for
    the color space.Look at the format specifications...
    By the way, do all image file types have different
    color space or could they all have the same color
    space, for example, RGB?They can have different color spaces. RGB, ARGB, CMYK, some Adobe format...

  • How do i covert an image in J2ME into an byte array ?

    Can anyone help to show me the way to convert an image into a byte array ?
    Thanks early reply appreciated.

    Hi! I�m developing an application to be installed in two devices. My problem is that i want to send an image: I can receive it with createImage(InputStream ip), but how can i send it with OutputStream? it needs a byte array (method write), how can i convert an image into a byte array?is there any other solution? like send it as a string...
    Thanks

  • 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

  • To create images continuously using a byte array  while streaming video

    Can someone please help me in creating images from a byte array continuously which is required while streaming video on implementation of RTP?

    seems like this could be the class you want to look at
    Package javax.imageio

  • Socket connection, byte array

    I've got a problem with byte array. It needs to be initialized f.e.
    byte[] data = new byte[100];However, I'm gonna read input stream to that array
    is.read(data);and input stream might be longer than expected f.e. 1000 bytes.
    What can I do to predict the length of byte[] or avoid NullPointerException
    public void connect() throws IOException {SocketConnection client = (SocketConnection) Connector.open("socket://" + hostname + ":" + port);
    client.setSocketOption(client.DELAY, 0);
    client.setSocketOption(client.KEEPALIVE, 0);
    InputStream is = client.openInputStream();
    OutputStream os = client.openOutputStream();
    os.write("some string".getBytes());
    int c = 0;
    byte[] data = new byte[100];
    is.read(data);
    while((c = is.read()) != -1) {
    System.out.print((char)c);
    is.close();
    os.close();
    client.close();
    }

    excellent thanks
    for other users:
        public byte[] getBytes() throws IOException {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            SocketConnection client = (SocketConnection) Connector.open("socket://" + hostname + ":" + port);
            client.setSocketOption(client.DELAY, 0);
            client.setSocketOption(client.KEEPALIVE, 0);
            InputStream is = client.openInputStream();
            OutputStream os = client.openOutputStream();
            os.write("some string".getBytes());
            int c = 0;
            while((c = is.read()) != -1) {
                baos.write(c);
            is.close();
            os.close();
            client.close();
            return baos.toByteArray();
        }

  • UnmarshalException for large byte array :: Weblogic 8.1 SP2

    Hi,
    1) We have a application running on Weblogic 8.1SP2.
    2) Our scenario consist of Client code which reads a input file via Stream and converts it to a byte array before sending it to the Server.
    When the server side code calls the Remote Bean (with byte array as an argument) it throws this exception :
    "java.rmi.UnmarshalException: Software caused connection abort: socket write error"
    Intermittently also got this error :: "weblogic.rjvm.PeerGoneException: ; nested exception is: java.io.EOFException"
    3) This scenario works absolutely fine if the said Input File is of a smaller size.
    4) I have also set the following params in config.xml <server .../> tag, but all in vain:
         CompleteMessageTimeout="480" also tried with "0"
         MaxMessageSize="2000000000"
         NativeIOEnabled="true"
    Also tried with :
         MaxHTTPMessageSize="2000000000" & MaxT3MessageSize="2000000000"
    Below is the exception trace:
    java.rmi.UnmarshalException: Software caused connection abort: socket write error; nested exception is: java.net.SocketException: Software caused connection abort: socket write error
    java.rmi.UnmarshalException: Software caused connection abort: socket write error; nested exception is: java.net.SocketException: Software caused connection abort: socket write error at weblogic.rmi.cluster.ReplicaAwareRemoteRef.invoke(ReplicaAwareRemoteRef.java:297)
         at weblogic.rmi.cluster.ReplicaAwareRemoteRef.invoke(ReplicaAwareRemoteRef.java:244)
    Caused by: java.net.SocketException: Software caused connection abort: socket write error
         at weblogic.rjvm.BasicOutboundRequest.sendReceive(BasicOutboundRequest.java:108)
         at weblogic.rmi.cluster.ReplicaAwareRemoteRef.invoke(ReplicaAwareRemoteRef.java:284)
         ... 6 more
    Caused by: java.net.SocketException: Software caused connection abort: socket write error
         at java.net.SocketOutputStream.socketWrite0(Native Method)
         at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
         at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
         at weblogic.socket.SocketMuxer.write(SocketMuxer.java:721)
         at weblogic.rjvm.t3.T3JVMConnection.sendMsg(T3JVMConnection.java:723)
         at weblogic.rjvm.MsgAbbrevJVMConnection.sendOutMsg(MsgAbbrevJVMConnection.java:276)
         at weblogic.rjvm.MsgAbbrevJVMConnection.sendMsg(MsgAbbrevJVMConnection.java:164)
         at weblogic.rjvm.ConnectionManager.sendMsg(ConnectionManager.java:549)
         at weblogic.rjvm.RJVMImpl.send(RJVMImpl.java:722)
         at weblogic.rjvm.MsgAbbrevOutputStream.flushAndSendRaw(MsgAbbrevOutputStream.java:292)
         at weblogic.rjvm.MsgAbbrevOutputStream.flushAndSend(MsgAbbrevOutputStream.java:300)
         at weblogic.rjvm.MsgAbbrevOutputStream.sendRecv(MsgAbbrevOutputStream.java:322)
         at weblogic.rjvm.BasicOutboundRequest.sendReceive(BasicOutboundRequest.java:103)
         ... 7 more
    Any thoughts would be helpful?
    Thanks,
    Khyati

    Hi,
    1) We have a application running on Weblogic 8.1SP2.
    2) Our scenario consist of Client code which reads a input file via Stream and converts it to a byte array before sending it to the Server.
    When the server side code calls the Remote Bean (with byte array as an argument) it throws this exception :
    "java.rmi.UnmarshalException: Software caused connection abort: socket write error"
    Intermittently also got this error :: "weblogic.rjvm.PeerGoneException: ; nested exception is: java.io.EOFException"
    3) This scenario works absolutely fine if the said Input File is of a smaller size.
    4) I have also set the following params in config.xml <server .../> tag, but all in vain:
         CompleteMessageTimeout="480" also tried with "0"
         MaxMessageSize="2000000000"
         NativeIOEnabled="true"
    Also tried with :
         MaxHTTPMessageSize="2000000000" & MaxT3MessageSize="2000000000"
    Below is the exception trace:
    java.rmi.UnmarshalException: Software caused connection abort: socket write error; nested exception is: java.net.SocketException: Software caused connection abort: socket write error
    java.rmi.UnmarshalException: Software caused connection abort: socket write error; nested exception is: java.net.SocketException: Software caused connection abort: socket write error at weblogic.rmi.cluster.ReplicaAwareRemoteRef.invoke(ReplicaAwareRemoteRef.java:297)
         at weblogic.rmi.cluster.ReplicaAwareRemoteRef.invoke(ReplicaAwareRemoteRef.java:244)
    Caused by: java.net.SocketException: Software caused connection abort: socket write error
         at weblogic.rjvm.BasicOutboundRequest.sendReceive(BasicOutboundRequest.java:108)
         at weblogic.rmi.cluster.ReplicaAwareRemoteRef.invoke(ReplicaAwareRemoteRef.java:284)
         ... 6 more
    Caused by: java.net.SocketException: Software caused connection abort: socket write error
         at java.net.SocketOutputStream.socketWrite0(Native Method)
         at java.net.SocketOutputStream.socketWrite(SocketOutputStream.java:92)
         at java.net.SocketOutputStream.write(SocketOutputStream.java:136)
         at weblogic.socket.SocketMuxer.write(SocketMuxer.java:721)
         at weblogic.rjvm.t3.T3JVMConnection.sendMsg(T3JVMConnection.java:723)
         at weblogic.rjvm.MsgAbbrevJVMConnection.sendOutMsg(MsgAbbrevJVMConnection.java:276)
         at weblogic.rjvm.MsgAbbrevJVMConnection.sendMsg(MsgAbbrevJVMConnection.java:164)
         at weblogic.rjvm.ConnectionManager.sendMsg(ConnectionManager.java:549)
         at weblogic.rjvm.RJVMImpl.send(RJVMImpl.java:722)
         at weblogic.rjvm.MsgAbbrevOutputStream.flushAndSendRaw(MsgAbbrevOutputStream.java:292)
         at weblogic.rjvm.MsgAbbrevOutputStream.flushAndSend(MsgAbbrevOutputStream.java:300)
         at weblogic.rjvm.MsgAbbrevOutputStream.sendRecv(MsgAbbrevOutputStream.java:322)
         at weblogic.rjvm.BasicOutboundRequest.sendReceive(BasicOutboundRequest.java:103)
         ... 7 more
    Any thoughts would be helpful?
    Thanks,
    Khyati

Maybe you are looking for

  • Time Machine backup/restore on iMac with SSD and HD...

    Time Machine backs up the SSD and HD on my iMac into one "sparse bundle" for the computer.  I need some direction on how to get to the HD backup in order to restore individual files and folders.  PLEASE do not give an answer like "Just enter Time Mac

  • Can you design a filter in a sequence and then save it?

    I made a cool little filter that consists of a couple of alpha video files that I might like to use for future videos. Is there any way I can save it as a filter in my effects/filters folder in final cut Por 5. or in my favorites folder. Thanks I app

  • Problem with "Confirmation" changes in PO using ORDRSP Idoc

    Hi all, I have an issue when changing "Confirmations" tab in PO. I configured Output Message Z001 that should be determined when I change values in that tab. That scenario is working fine, but the real change will be done by ORDRSP Idoc. Using that I

  • OT: question about multiple root directories

    ok, so on this website i just transferred to a new host, i password protected a directory, and for many people (possibly everyone) it is asking for the login info twice or three times before it lets you in. i contacted the host tech support, who gave

  • PSEv4: Templates for creating album pages

    My wife and I just got PSEv4, and have been having fun with the creation tools --specifically the photo album page creator. But (there's always a but)... We're already feeling like the templates available are limiting, and would like to have more opt