Unable 2 read bytes array of images

I have made a client application which will
receive an image from server
the mobile app (clent) is reveiving bytes array in emulator
but unable 2 receive it in real application...
message = new byte[2073]; //string 2 read pic;
for(i=0;i<2073;i++)
//read pic array byte by byte
x=is.read(); //(is is an input stream)
message= (byte)x;
// also tried this
//is.read(message)
works fine in emulator but not in real appication in sony erricson k310i

sorry actually code was.....
for reading byte by byte...............
message = new byte[2073]; //string 2 read pic;
for(a=0;a<2073;a++)
//read pic array byte by byte
x=is.read(); //(is is an input stream)
message[a]= (byte)x; //problem in last post i[] //converting it into italic
//for reading whole array message
// also tried this
is.read(message)
and i think there shall be no problem in converting an[b] int into byte

Similar Messages

  • How to add byte[] array based Image to the SQL Server without using parameter

    how to add byte[] array based Image to the SQL Server without using parameter.I have a column in table with the type image in sql and i want to add image array to the sql image column like below:
    I want to add image (RESIM) to the procedur like shown above but sql accepts byte[] RESIMI like System.Drowing. I whant that  sql accepts byte [] array like sql  image type
    not using cmd.ParametersAdd() method
    here is Isle() method content

    SQL Server binary constants use a hexadecimal format:
    https://msdn.microsoft.com/en-us/library/ms179899.aspx
    You'll have to build that string from a byte array yourself:
    byte[] bytes = ...
    StringBuilder builder = new StringBuilder("0x", 2 + bytes.Length * 2);
    foreach (var b in bytes)
    builder.Append(b.ToString("X2"));
    string binhex = builder.ToString();
    That said, what you're trying to do - not using parameters - is the wrong thing to do. Not only it is insecure due to the risk of SQL injection but in the case of binary data is also inefficient since these hex strings are larger than the original byte[]
    data.

  • How to change the image into byte and byte array into image

    now i am developing one project. i want change the image into byte array and then byte array into image.

    FileInputStream is = new FileInputStream(file);
    byte[] result = IOUtils.toByteArray(is);
    with apache common IO lib

  • 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" />

  • How to send byte array of image with 300dpi.

    Hello fiends
                       i am making an application in which i have to send the byte array of an image with 300dpi.
    so i am using image snapshot class for that and use that code.
                        var snapshot:ImageSnapshot = ImageSnapshot.captureImage(cnvParent,300);
                        var bdata:String = ImageSnapshot.encodeImageAsBase64(snapshot);
    but when i send that bdata to php end using httpService.The size at other end of image increases surprisingly.i means it will increase its actual height and actual width.so is there any way to overcome this increase in size when i bitmapped image at 300 dpi?
    if there any way then please tell me.waiting for your reply.
    Thanks and Regards
        Vineet Osho

    Thanks david for such a quick reply.the link is really helpful.So we have to calculate the screendpi thruogh our code and then set the height and width of image.is there any simple way to sort out my problem.i just want to print my image at 300dpi but i am using image snapshot class so its taking the snap of my container(image) and save the image at 96 dpi which is dpi of my screen(monitor).so is there any way or any class in flex through which i got the image at its original dpi.i am not stick on 300 dpi but i m getting image from backend through xml at 300dpi.thats why i want the byte array i am sending should be at 300dpi.i am totally confused now.so please help me.
    Thanks and regards
      Vineet osho

  • Issue with reading byte array

    I have a binary file to be read.I want to read the whole file into a byte array. But while doing so the values which are greater than 128 are read as negative values as we have Signedbyte in java(-127 to 128).
    So I tried reading the bytes into the int array as shown in the below code.
    int i = 0;
         int content[]= new int[(int)size];
         FileInputStream fstream = new FileInputStream(fileName);
         DataInputStream in = new DataInputStream(fstream);
         while(i<size)
         content= in.readUnsignedByte();
         i++;
    The above function 'readUnsignedByte();' reads byte and stores it into an int array.....But since the file contains around 34000 bytes ....the loop runs 340000 times .....which is a performance hazard.
    After googling for hours ....I could still not find any alternative ....
    I want to read byte and want to store in int array but instead of loop, I want to read the file at once.
    Or is there any way to implement Unsigned Byte in java so that I can read the entire file in byte array without corrupting the values which are greater than 128..
    I have to deliver the code asap .....Please help me out with an alternative solution for this...
    Thanks in advance....

    Thanks for replying ......
    Actually, I need to take the bytes into an array(int or byte array) with decimal values and further process these decimal values.......
    but while reading the file into a byte array the decimal values get corrupted(in case when I read a number greater than 128) but in this case I am able to read the whole file at once(without using any loop) as done by the following code
         FileInputStream fstream = new FileInputStream(fileName);
         DataInputStream in = new DataInputStream(fstream);
         byte b[] = null;
         in.readFully(b);
    and while reading the file in int array as done in the below code is inefficient as the number of times the loop runs is more than 34000..... please suggest me some alternative.
    int i = 0;
         int content[]= new int[(int)size];
         FileInputStream fstream = new FileInputStream(fileName);     
         DataInputStream in = new DataInputStream(fstream);
         while(i<size)
                   content= in.readUnsignedByte();
                   i++;

  • Reducing size of Image or byte array

    Hello,
    I am making a program where i have to send user's screen to another PC,
    So I use class Robot to make a screen capture and send it via UDP.
    However this is still too slow, my question is: is there some library to compress the size of byte array or Image?
    Thanks for help,
    Juraj

    thanks for help i found it
    byte[] input = ...;
    // Create the compressor with highest level of compression
    Deflater compressor = new Deflater();
    compressor.setLevel(Deflater.BEST_COMPRESSION);
    // Give the compressor the data to compress
    compressor.setInput(input);
    compressor.finish();

  • 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)?

  • 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

  • Read Video data from buffer or byte array

    Hi guys,
    I've developed a tx/rx module, the tx read an mpg file and transfer it over network. rx has the data in a byte array, I also feed the byte array to a media buffer. Now my question is how to creat the player and feed the player to play the content of the buffer or byte array?
    I would really appreaciate if someone could help me please...
    Thanx
    I haven't and didn't want to use any of the RTP stuff...

    Hi, I tried PullBufferDataSource. What I am trying to do is : read a .wav file into a queue, then construct a datasource with this queue. The processor will be contructed to process the datasource, and a datasink to sink data to a file. I think if this workflow could work, it should work in network transmission.
    In fact the code works partially. The trick part is the read( Buffer ) method. If I try to use 'if' statement to see if Queue has empty or not, the datasink could not format the head part of output file correctly. If I didnot use 'if' statement, the program will terminate when exception occurs. The output file is all right.
    I did not understand what is going on.
    Note: the original file is a RAW data file without format info.
    Here is the code fragments. Hopefully we can work together to figure it out.
    Thanks.
    Jim
    * QueueDataSourceTester.java
    * Created on November 11, 2002, 10:29 AM
    package bonephone;
    import javax.media.*;
    import javax.media.control.*;
    import javax.media.protocol.*;
    import javax.media.datasink.*;
    import javax.media.format.AudioFormat;
    import java.util.LinkedList;
    import java.io.*;
    * @author wguo
    public class QueueDataSourceTester implements ControllerListener, DataSinkListener {
    protected LinkedList myQueue;
    /** Creates a new instance of QueueDataSourceTester */
    public QueueDataSourceTester() {
    myQueue = new LinkedList();
    public void testIt( ){
    // Read a file into a Queue
    FileInputStream inputStream = null;
    try{
    inputStream = new FileInputStream( "c:/media/phone.wav");
    catch( IOException ioe ){
    System.err.println( "Error on open media file." );
    try{
    byte data[] = new byte[1024];
    int n ;
    while( ( n = inputStream.read( data, 0, 1024 )) != -1 ){
    myQueue.addLast( data );
    data = new byte[1024];
    inputStream.close();
    catch( IOException ioe ){
    System.err.println( "Error on reading file." );
    System.out.println( "Queue Size: " + myQueue.size() );
    System.out.println( "myQueue = " + myQueue.size() );
    QueueDataSource dataSource = new QueueDataSource( myQueue );
    Processor p = null ;
    try{
    System.out.println( "Create processor for QueueDataSource ... " );
    p = Manager.createProcessor( dataSource );
    catch( Exception e ){
    System.err.println( "Cannot create a processor for the QueueDataSource. " );
    System.out.println( "\nProcessor is created." );
    p.addControllerListener( this );
    p.configure();
    if( !waitForState( p, p.Configured ) ) {
    System.err.println( "Failed to configure the processor." );
    System.out.println( "\nProcessor is configured") ;
    // p.setContentDescriptor( new ContentDescriptor( ContentDescriptor.RAW ) );
    p.setContentDescriptor( new ContentDescriptor( FileTypeDescriptor.WAVE ) );
    TrackControl tcs[] = p.getTrackControls();
    Format f[] = tcs[0].getSupportedFormats();
    if( f == null || f.length == 0 ){
    System.err.println( "The mux does not support the input format : "+ tcs[0].getFormat() );
    tcs[0].setFormat(
    new AudioFormat( AudioFormat.ULAW,
    8000,
    8,
    1,
    Format.NOT_SPECIFIED,
    AudioFormat.SIGNED,
    8,
    Format.NOT_SPECIFIED,
    Format.byteArray ) );
    //System.out.println( "Setting the track format to: " + f[4] );
    p.realize();
    if( !waitForState( p, p.Realized )){
    System.err.println( "Failed to realize the processor" );
    DataSink dsink;
    MediaLocator outML = new MediaLocator("file:/c:/media/queue.wav" );
    if( (dsink = createDataSink( p, outML )) == null ){
    System.err.println( "Failed to create a datasink for given " +
    "mediaLocator : " + outML );
    dsink.addDataSinkListener( this );
    System.out.println( "\nProcessor is realized" );
    try{
    p.start();
    dsink.start();
    catch( IOException ioe ){
    System.err.println( "IO error during processing." );
    waitForFileDone();
    try{
    dsink.close();
    catch( Exception e ){
    p.removeControllerListener( this );
    System.err.println( "... done processing." );
    DataSink createDataSink( Processor p, MediaLocator outML ){
    DataSource ds ;
    if( ( ds = p.getDataOutput() ) == null ) {
    System.err.println( "Something is really wrong: the processor does" +
    " not have an output DataSource. " );
    return null;
    System.out.println( "DataOutput: " + ds.getContentType() );
    DataSink dsink;
    try{
    System.out.println( "- create DataSink for : " + outML );
    dsink = Manager.createDataSink( ds, outML );
    dsink.open();
    catch( Exception e ){
    System.err.println( "Cannot create the DataSink: " + e );
    return null;
    return dsink;
    Object waitSync = new Object();
    boolean stateTransitionOK = true;
    boolean waitForState( Processor p, int state ){
    synchronized( waitSync ){
    try{
    while( p.getState() < state && stateTransitionOK )
    waitSync.wait();
    catch( Exception e ){
    return stateTransitionOK;
    public void controllerUpdate(javax.media.ControllerEvent controllerEvent) {
    if( controllerEvent instanceof ConfigureCompleteEvent ||
    controllerEvent instanceof RealizeCompleteEvent ||
    controllerEvent instanceof PrefetchCompleteEvent ){
    synchronized( waitSync ){
    stateTransitionOK = true;
    waitSync.notifyAll();
    } else if( controllerEvent instanceof ResourceUnavailableEvent ){
    synchronized( waitSync ){
    stateTransitionOK = false;
    waitSync.notifyAll( );
    public static void main( String args[] ){
    QueueDataSourceTester tester = new QueueDataSourceTester();
    tester.testIt();
    Object waitFileSync = new Object();
    boolean fileDone = false;
    boolean fileSuccess = true;
    boolean waitForFileDone(){
    synchronized( waitFileSync ){
    try{
    waitFileSync.wait( 5000 );
    catch( Exception e ){
    System.err.println( "Error on waiting file to be done" );
    return fileSuccess;
    public void dataSinkUpdate(javax.media.datasink.DataSinkEvent dataSinkEvent) {
    if( dataSinkEvent instanceof EndOfStreamEvent ){
    synchronized( waitFileSync ){
    fileDone = true;
    waitFileSync.notifyAll();
    else if ( dataSinkEvent instanceof DataSinkErrorEvent ){
    synchronized( waitFileSync ){
    fileDone = true;
    fileSuccess = false;
    waitFileSync.notifyAll();
    // Inner Class
    * A datasource that will read Media data from Queue.
    * Inside queue individual RAW data packats are stored.
    * @author wguo
    public class QueueDataSource extends PullBufferDataSource{
    protected QueueSourceStream streams[];
    /** Creates a new instance of QueueDataSource */
    public QueueDataSource( LinkedList source ) {
    printDebug( "QueueDataSource: QueueDataSource( LinkedList) " );
    streams = new QueueSourceStream[1];
    streams[0] = new QueueSourceStream( source );
    public void connect() throws java.io.IOException {
    printDebug( "QueueDataSource: connect() " );
    public void disconnect() {
    printDebug( "QueueDataSource: disconnect()" );
    public String getContentType() {
    return ContentDescriptor.RAW;
    public Object getControl(String str) {
    printDebug( "QueueDataSource: getControl(String) " );
    return null;
    public Object[] getControls() {
    printDebug( "QueueDataSource: getControls() " );
    return new Object[0];
    public javax.media.Time getDuration() {
    return DURATION_UNKNOWN;
    public javax.media.protocol.PullBufferStream[] getStreams() {
    printDebug( "QueueDataSource: getStreams() " );
    return streams;
    public void start() throws java.io.IOException {
    printDebug( "QueueDataSource:start()" );
    public void stop() throws java.io.IOException {
    printDebug( "QueueDataSource: stop() " );
    private void printDebug( String methodInfo ){
    System.out.println( methodInfo + " is called" );
    // Inner Class
    public class QueueSourceStream implements PullBufferStream{
    LinkedList sourceQueue;
    AudioFormat audioFormat;
    boolean ended = false;
    /** Creates a new instance of QueueSourceStream */
    public QueueSourceStream( LinkedList sourceQueue ) {
    printDebug( "QueueSourceStream: QueueSourceStream( LinkedList )" );
    this.sourceQueue = sourceQueue;
    audioFormat = new AudioFormat(
    AudioFormat.ULAW,
    8000,
    8,
    1,
    Format.NOT_SPECIFIED,
    AudioFormat.SIGNED,
    8,
    Format.NOT_SPECIFIED,
    Format.byteArray);
    public boolean endOfStream() {
    printDebug( "QueueSourceStream: endOfStream()" );
    return ended;
    public javax.media.protocol.ContentDescriptor getContentDescriptor() {
    printDebug( "QueueSourceStream: getContentDescriptor()" );
    return new ContentDescriptor( ContentDescriptor.RAW) ;
    public long getContentLength() {
    printDebug( "QueueSourceStream:getContentLength()" );
    return 0;
    public Object getControl(String str) {
    printDebug( "QueueSourceStream:getControl( String) " );
    return null;
    public Object[] getControls() {
    printDebug( "QueueSourceStream:getControls()" );
    return new Object[0];
    public javax.media.Format getFormat() {
    printDebug( "QueueSourceStream:getFormat()" );
    return audioFormat;
    public void read(javax.media.Buffer buffer) throws java.io.IOException {
    buffer.setData( (byte[])sourceQueue.removeFirst() );
    buffer.setOffset( 0 );
    buffer.setLength( 1024 );
    buffer.setFormat( audioFormat );
    printDebug( "QueueSourceStream: read( Buffer ) " );
    else {
    buffer.setEOM( true );
    buffer.setOffset( 0 );
    buffer.setLength( 0 );
    ended = true;
    System.out.println( "Done reading byte array" );
    return;
    public boolean willReadBlock() {
    printDebug( "QueueSourceStream: willReadBlock()" );
    if( myQueue.isEmpty() )
    return true;
    else
    return false;
    private void printDebug( String methodInfo ){
    System.out.println( methodInfo + " is called. " );

  • How do I read directly from file into byte array

    I am reading an image from a file into a BuffertedImage then writing it out again into an array of bytes which I store and use later on in the program. Currently Im doing this in two stages is there a way to do it it one go to speed things up.
    try
                //Read File Contents into a Buffered Image
                /** BUG 4705399: There was a problem with some jpegs taking ages to load turns out to be
                 * (at least partially) a problem with non-standard colour models, which is why we set the
                 * destination colour model. The side effect should be standard colour model in subsequent reading.
                BufferedImage bi = null;
                ImageReader ir = null;
                ImageInputStream stream =  ImageIO.createImageInputStream(new File(path));
                final Iterator i = ImageIO.getImageReaders(stream);
                if (i.hasNext())
                    ir = (ImageReader) i.next();
                    ir.setInput(stream);
                    ImageReadParam param = ir.getDefaultReadParam();
                    ImageTypeSpecifier typeToUse = null;
                    for (Iterator i2 = ir.getImageTypes(0); i2.hasNext();)
                        ImageTypeSpecifier type = (ImageTypeSpecifier) i2.next();
                        if (type.getColorModel().getColorSpace().isCS_sRGB())
                            typeToUse = type;
                    if (typeToUse != null)
                        param.setDestinationType(typeToUse);
                    bi = ir.read(0, param);
                    //ir.dispose(); seem to reference this in write
                    //stream.close();
                //Write Buffered Image to Byte ArrayOutput Stream
                if (bi != null)
                    //Convert to byte array
                    final ByteArrayOutputStream output = new ByteArrayOutputStream();
                    //Try and find corresponding writer for reader but if not possible
                    //we use JPG (which is always installed) instead.
                    final ImageWriter iw = ImageIO.getImageWriter(ir);
                    if (iw != null)
                        if (ImageIO.write(bi, ir.getFormatName(), new DataOutputStream(output)) == false)
                            MainWindow.logger.warning("Unable to Write Image");
                    else
                        if (ImageIO.write(bi, "JPG", new DataOutputStream(output)) == false)
                            MainWindow.logger.warning("Warning Unable to Write Image as JPEG");
                    //Add to image list
                    final byte[] imageData = output.toByteArray();
                    Images.addImage(imageData);
                  

    If you don't need to manipulate the image in any way I would suggest you just read the image file directly into a byte array (without ImageReader) and then create the BufferedImage from that byte array.

  • How to get a string or byte array representation of an Image/BufferedImage?

    I have a java.awt.Image object that I want to transfer to a server application (.NET) through a http post request.
    To do that I would like to encode the Image to jpeg format and convert it to a string or byte array to be able to send it in a way that the receiver application (.NET) could handle. So, I've tried to do like this.
    private void send(Image image) {
        int width = image.getWidth(null);
        int height = image.getHeight(null);
        try {
            BufferedImage buffImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            ImageIcon imageIcon = new ImageIcon(image);
            ImageObserver observer = imageIcon.getImageObserver();
            buffImage.getGraphics().setColor(new Color(255, 255, 255));
            buffImage.getGraphics().fillRect(0, 0, width, height);
            buffImage.getGraphics().drawImage(imageIcon.getImage(), 0, 0, observer);
            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            JPEGImageEncoder jpeg = JPEGCodec.createJPEGEncoder(stream);
            jpeg.encode(buffImage);
            URL url = new URL(/* my url... */);
            URLConnection connection = url.openConnection();
            String boundary = "--------" + Long.toHexString(System.currentTimeMillis());
            connection.setRequestProperty("method", "POST");
            connection.setRequestProperty("Content-Type", "multipart/form-data; boundary=" + boundary);
            String output = "--" + boundary + "\r\n"
                          + "Content-Disposition: form-data; name=\"myImage\"; filename=\"myFilename.jpg\"\r\n"
                          + "Content-Type: image/jpeg\r\n"
                          + "Content-Transfer-Encoding: base64\r\n\r\n"
                          + new String(stream.toByteArray())
                          + "\r\n--" + boundary + "--\r\n";
            connection.setDoOutput(true);
            connection.getOutputStream().write(output.getBytes());
            connection.connect();
        } catch {
    }This code works, but the image I get when I save it from the receiver application is distorted. The width and height is correct, but the content and colors are really weird. I tried to set different image types (first line inside the try-block), and this gave me different distorsions, but no image type gave me the correct image.
    Maybe I should say that I can display the original Image object on screen correctly.
    I also realized that the Image object is an instance of BufferedImage, so I thought I could skip the first six lines inside the try-block, but that doesn't help. This way I don't have to set the image type in the constructor, but the result still is color distorted.
    Any ideas on how to get from an Image/BufferedImage to a string or byte array representation of the image in jpeg format?

    Here you go:
      private static void send(BufferedImage image) throws Exception
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageIO.write(image, "jpeg", byteArrayOutputStream);
        byte[] imageByteArray = byteArrayOutputStream.toByteArray();
        URL url = new URL("http://<host>:<port>");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setDoOutput(true);
        connection.setRequestMethod("POST");
        OutputStream outputStream = connection.getOutputStream();
        outputStream.write(imageByteArray, 0, imageByteArray.length);
        outputStream.close();
        connection.connect();
        // alternative to connect is to get & close the input stream
        // connection.getInputStream().close();
      }

  • Byte array convert to image works fine for a peiod of time, Then error

    Hi all
    I'm on a program of reading incoming image set which comes as byte arrays through socket and convert them back to images using the method.
    javax.microedition.lcdui.Image.createImage();This works perfect for some time.
    But after 1 minute of running it gives an error
    java.lang.OutOfMemoryError: Java heap space
            at java.awt.image.BufferedImage.getRGB(Unknown Source)
            at com.sun.kvem.midp.GraphicsBridge.loadImage(Unknown Source)
            at com.sun.kvem.midp.GraphicsBridge.createImageFromData(Unknown Source)
            at sun.reflect.GeneratedMethodAccessor14.invoke(Unknown Source)
            at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
            at java.lang.reflect.Method.invoke(Unknown Source)
            at com.sun.kvem.sublime.MethodExecution.process(Unknown Source)
            at com.sun.kvem.sublime.SublimeExecutor.processRequest(Unknown Source)
            at com.sun.kvem.sublime.SublimeExecutor.run(Unknown Source)My J2ME client code
    public class ChangeImage extends Thread
        private SocketConnection sock = null;
        private Image img = null;
        private CanvasKey canvas = null;
        private InputStream in = null;
        public ChangeImage(SocketConnection sock, Canvas canvas) throws IOException
            this.sock = sock;
            this.canvas = (CanvasKey) canvas;
            in = sock.openInputStream();
        public void run()
            super.run();
            short length;
            while (true)
                DataInputStream din = null;
                try
                    din = new DataInputStream(in);
                    length = din.readShort();     // to determine next data packet size
                    byte[] arr = new byte[length];  // next data packet store here
                    din.readFully(arr);  //read image
                    img = Image.createImage(arr, 0, arr.length);
                    canvas.setImage(img);
                    ChangeImage.sleep(50);
                catch (Exception ex)
                    ex.printStackTrace();
    }When I comment following line no error prints.
    img = Image.createImage(arr, 0, arr.length);So the problem is not with socket program.
    What is this problem? Think old image isn't being flushed!!! in the method javax.microedition.lcdui.Image.createImage();Please help me.

    Forgot to Mention i'm using Windows 8.1 - 32 GB Ram - i7-3970x - 2 SSd's in raid 0 for C Drive/ Storage drive is three ( 2 tb HDD in a raid 0 ) / Pictures Folder defaults to the Storage Drive not the Application drive .

  • Create image from byte[]array on server side

    Hello everyone..
    I'm developing an application which will take snapshots from a mobile device, and send it to my pc via bluetooth. I have my own midlet which uses the phone camera to take the snapshot, i want to transfer that snapshot to my pc.
    The snapshot is taken is stored in an array byte.
    The image can be created on the phone itself with no problem using : image.createImage(byte[])
    my problem is that when i send the array byte via bluetooth, and receive it on the server, i cannot create the image using the :image.createImage() code
    The connection is good since i have tested by writing the content of the array in a text file.
    Piece of midlet code:
                try{
                     stream = (StreamConnection)Connector.open(url);
                     OutputStream ggt = stream.openOutputStream();
                     ggt.write(str);
                     ggt.close();
                }catch(Exception e){
                     err1  = e.getMessage();
                }where str is my array byte containing the snapshot
    And on my server side:
    Thread th = new Thread(){
                   public void run(){
                        try{
                             while(true){
                                  byte[] b = new byte[in.read()];
                                  int x=0;
                                  System.out.println("reading");
                                  r = in.read(b,0,b.length);
                                  if (r!=0){
                                       System.out.println(r);     
                                       img = Image.createImage(b, 0, r);
                                                            //other codes
                                       i get this error message:
    Exception in thread "Thread-0" java.lang.UnsatisfiedLinkError: javax.microedition.lcdui.ImmutableImage.decodeImage([BII)V
         at javax.microedition.lcdui.ImmutableImage.decodeImage(Native Method)
         at javax.microedition.lcdui.ImmutableImage.<init>(Image.java:906)
         at javax.microedition.lcdui.Image.createImage(Image.java:367)
         at picserv2$1.run(picserv2.java:70)
    Please anyone can help me here? is this the way to create the image on the server side? thx a lot

    here is exactly how i did it :
    while(true){
                                  byte[] b = new byte[in.read()];
                                  System.out.println("reading");
                                  r = in.read(b, 0, b.length);
                                  if (r!=0){
                                       Toolkit toolkit = Toolkit.getDefaultToolkit();
                                       Image img = toolkit.createImage(b, 0, b.length);
                                       JLabel label = new JLabel(new ImageIcon(img) );
                                       BufferedImage bImage = new BufferedImage(img.getWidth(label),img.getHeight(label),BufferedImage.TYPE_INT_RGB);
                                       bImage.createGraphics().drawImage(img, 0,0,null);
                                       File xd = new File("D:/file.jpg");
                                       ImageIO.write(bImage, "jpg", xd);
                                       System.out.println("image sent");
                             }Edited by: jin_a on Mar 22, 2008 9:58 AM

  • 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();

Maybe you are looking for