Problem in reading an Image file from a Output Stream.

I am having problem reading a JPEG file. Actually i am sending JPEG file using UDP from the client. I am using this code to convert to a byte array to transmit the file:
DataInputStream inStream = new DataInputStream(new FileInputStream("src/Bgamex.jpg"));
String str1 = inStream.toString();
byte[] bindata = new byte[65500];
bindata = str1.getBytes();
On the server side, I am using these lines to convert the bytes to a file again but it seems to be that its not working. Its making file but with a bigger size & like garbage in it, showing nothing:
byte[] buf = new byte[65500];
// receive request
DatagramPacket packet = new DatagramPacket(buf, buf.length);
socket.receive(packet);
buf = packet.getData();
java.io.OutputStream fos = new java.io.FileOutputStream("Bga.jpg");
fos.write(buf);
Could somebody lemme know the problem in converting the file.
Thanx.

I propose you to perform this simple test to see by yourself:     final String BIN_FILENAME = "somebytes.bin";
    byte[] bin = {5, 4, 3, 2, 1};
    FileOutputStream out = new FileOutputStream(BIN_FILENAME);
    out.write(bin);
    out.flush();
    out.close();
    byte[] bindata;
    DataInputStream in1 = new DataInputStream(new FileInputStream(BIN_FILENAME));
    String str = in1.toString();
    in1.close();
    bindata = str.getBytes();   
    System.out.print("Bytes read with in1>");
    for (int i=0; i<bindata.length; i++) System.out.print(bindata);
System.out.println();
FileInputStream in2 = new FileInputStream(BIN_FILENAME);
bindata = new byte[65505];
int bread = in2.read(bindata, 0, in2.available());
in2.close();
System.out.print("Bytes read with in2>");
for (int i=0; i<bread; i++) System.out.print(bindata[i]);
System.out.println();

Similar Messages

  • Custom tag or help in reading an image file into the HTTP stream

    Since under WL we do not deploy our app physically there is no physical
              directory to write our dynamic images to (via kavachart).
              I can call their bean with:
              response.setContentType("image/png");
              ServletOutputStream output = response.getOutputStream();
              but that only allows the image back not the housing page. I can use an
              iframe but there are other issues and was wondering if anyone has idea on a
              custom tag the can easily read a physical directory outside of WL's space
              and include an image file in the http stream. Our app server and webservers
              are in separate zones so I can not just write to some virtual directory on
              the webserver and then serve it up w/ a simple <img> tag.
              BTW Kavachart has some tags referred to in their thin doc but I did not have
              good luck w/ their suggestions.
              Thanks in advance.
              dmg
              [email protected]
              

    Hi joe.com,
    Thanks for the response. It's greatly appreciated. Actually, I'm trying to run this on an Nokia SDK (s80 emulator) and eventually a windows mobile emulator.
    I was wondering if the JSR is the problem. I'm currently using jsr 62 and I'm thinking of trying to 216 to get PP 1.1. I'm wondering if 62 maybe limiting file io?
    any help is appreciated.

  • Reading only Image Files from a Directory and ignoring the rest

    i am wanting to be able to read a directory but only obtain the Image files (ie, gif, jpeg, tiff, png etc) and ignore all other type of files.
    i have made a custom ImageFIlter class which extends FileFilter which works for adding a photo singly, as only image files are shown in the JFileChooser. however i am wanting to add a folder of photos at once.
    here is the code so far:
    File dir;
                        JFileChooser fc = new JFileChooser();
                        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                        //Handle open button action.
                        int returnVal = fc.showOpenDialog(MainAppGUI.this);
                        if (returnVal == JFileChooser.APPROVE_OPTION) {
                             dir = fc.getSelectedFile();
                             if (dir.isDirectory()) {
                                  File[] files = dir.listFiles(new ImageFilter());
                                  for (int i = 0; i < files.length; i++) {
                                       if (files.isFile()) {
                                            try {
                                                 Photo PhotoAdded = workingCollection.addManyPhotos(files[i], canvas.getChangedMaxDim());
                                                 //need to also add it to the relevant vectors, ie
                                                 //for mouse over operations, or photos added after
                                                 //save.
                                                 if(!workingCollection.isDuplicate()){
                                                      photosToCheck.add(photoAdded);
                                                      canvas.addToGrid(photoAdded);
                                                      photosAddedAfterLoad.add(photoAdded);
                                                      canvas.repaint();
                                                 else{
                                                      //do nothing as it is already in the vectors.
                                            } catch (Exception er) {
                                                 // Do nothing. Bad mp3, don't add.
                                       // recurse through directories
                                       else {
                             } else {
                                  try {
                                       throw new IOException(
                                                 "Error loading files from a directory: "
                                                           + dir.getAbsolutePath() + " is not a "
                                                           + "directory");
                                  } catch (IOException e1) {
                                       // TODO Auto-generated catch block
                                       e1.printStackTrace();
    any ideas?

    I'm confused.
    You already ARE using a FileFilter to only pick up image files. Whats the problem?
    If you need to recurse directories you need to change your code only a little.
    Write your method
    JFileChooser fc = new JFileChooser();
    fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    //Handle open button action.
    int returnVal = fc.showOpenDialog(MainAppGUI.this);
    if (returnVal == JFileChooser.APPROVE_OPTION) {
      dir = fc.getSelectedFile();
    if (dir.isDirectory()) {
      scanDirectory(dir);
    else{
      // not a directory
    public void scanDirectoryForPhotos(File directory){
      // taking your code
    if (dir.isDirectory()) {
      File[] files = dir.listFiles(new ImageFilter());
      for (int i = 0; i < files.length; i++) {
        if (files.isFile()) {
    // details deleted
    // recurse through directories
    else {
    scanDirectory(files[i]);
    Your exception handling is a little strange. You throw an exception only to catch it immediately to print a stack trace? Not exactly the most common handling I've seen. You should probably just throw the exception and let the next level down handle it.
    Cheers,
    evnafets

  • Reading only Image files from a directory

    i am wanting to be able to read a directory but only obtain the Image files (ie, gif, jpeg, tiff, png etc) and ignore all other type of files.
    i have made a custom ImageFIlter class which extends FileFilter which works for adding a photo singly, as only image files are shown in the JFileChooser. however i am wanting to add a folder of photos at once.
    here is the code so far:
    File dir;
                        JFileChooser fc = new JFileChooser();
                        fc.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
                        //Handle open button action.
                        int returnVal = fc.showOpenDialog(MainAppGUI.this);
                        if (returnVal == JFileChooser.APPROVE_OPTION) {
                             dir = fc.getSelectedFile();
                             if (dir.isDirectory()) {
                                  File[] files = dir.listFiles(new FileFilter());
                                  for (int i = 0; i < files.length; i++) {
                                       if (files.isFile()) {
                                            try {
                                                 Photo PhotoAdded = workingCollection.addManyPhotos(files[i], canvas.getChangedMaxDim());
                                                 //need to also add it to the relevant vectors, ie
                                                 //for mouse over operations, or photos added after
                                                 //save.
                                                 if(!workingCollection.isDuplicate()){
                                                      photosToCheck.add(photoAdded);
                                                      canvas.addToGrid(photoAdded);
                                                      photosAddedAfterLoad.add(photoAdded);
                                                      canvas.repaint();
                                                 else{
                                                      //do nothing as it is already in the vectors.
                                            } catch (Exception er) {
                                                 // Do nothing. Bad mp3, don't add.
                                       // recurse through directories
                                       else {
                             } else {
                                  try {
                                       throw new IOException(
                                                 "Error loading files from a directory: "
                                                           + dir.getAbsolutePath() + " is not a "
                                                           + "directory");
                                  } catch (IOException e1) {
                                       // TODO Auto-generated catch block
                                       e1.printStackTrace();
    any ideas?

    it shouldnt be new FileFilter() there, it should be new ImageFilter() but it gives a compilation error saying i cannot apply that parameter to the listFiles() method in the File class

  • How use PHP to read image files from a folder and display them in Flex 3 tilelist.

    Hello. I need help on displaying images from a folder dynamically using PHP and display it on FLEX 3 TileList. Im currently able to read the image files from the folder but i don't know how to display them in the TileList. This is my current code
    PHP :
    PHP Code:
    <?php
    //Open images directory
    $imglist = '';
    $dir = dir("C:\Documents and Settings\april09mpsip\My Documents\Flex Builder 3\PHPTEST\src\Assets\images");
    //List files in images directory
    while (($file = $dir->read()) !== false)
    if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file))
    echo "filename: " . $file . "\n";
    $dir->close();
    ?>
    FLEX 3 :
    Code:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="absolute" creationComplete="pic.send();">
    <mx:Script>
    <![CDATA[
    import mx.controls.Alert;
    import mx.events.FlexEvent;
    import mx.rpc.events.FaultEvent;
    import mx.events.ItemClickEvent;
    import mx.rpc.events.ResultEvent;
    public var image:Object;
    private function resultHandler(event:ResultEvent):void
    image = (event.result);
    ta1.text = String(event.result);
    private function faultHandler(event:FaultEvent):void
    ta1.text = "Fault Response from HTTPService call:\n ";
    ]]>
    </mx:Script>
    <mx:TileList x="31" y="22" initialize="init();" dataProvider = "{image}" width="630" height="149"/>
    <mx:String id="phpPicture">http://localhost/php/Picture.php</mx:String>
    <mx:HTTPService id="pic" url="{phpPicture}" method="POST"
    result="{resultHandler(event)}" fault="{faultHandler(event)}"/>
    <mx:TextArea x="136" y="325" width="182" height="221" id="ta1" editable="false"/>
    <mx:Label x="136" y="297" text="List of files in the folder" width="182" height="20" fontWeight="bold" fontSize="13"/>
    </mx:Application>
    Thanks. Need help as soon as possbile. URGENT.

    i have made some changes, in the php part too, and following is the resulting code( i tried it, and found that it works.):
    PHP Code:
    <?php
    echo '<?xml version="1.0" encoding="utf-8"?>';
    ?>
    <root>
    <images>
    <?php
    //Open images directory
    $dir = dir("images");
    //List files in images directory
    while (($file = $dir->read()) !== false)
    if (eregi("gif", $file) || eregi("jpg", $file) || eregi("png", $file))
    echo "<image>" . $file . "</image>"; // i expect you to use the relative path in $dir, not C:\..........
    //$dir->close();
    ?>
    </images>
    </root>
    Flex Code:
    <?xml version="1.0" encoding="utf-8"?>
    <mx:Application xmlns:mx="http://www.adobe.com/2006/mxml"
    layout="absolute"
    creationComplete="callPHP();">
    <mx:Script>
    <![CDATA[
    import mx.rpc.http.HTTPService;
    import mx.controls.Alert;
    import mx.events.FlexEvent;
    import mx.rpc.events.FaultEvent;
    import mx.events.ItemClickEvent;
    import mx.collections.ArrayCollection;
    import mx.rpc.events.ResultEvent;
    [Bindable]
    private var arr:ArrayCollection = new ArrayCollection();
    private function callPHP():void
    var hs:HTTPService = new HTTPService();
    hs.url = 'Picture.php';
    hs.addEventListener( ResultEvent.RESULT, resultHandler );
    hs.addEventListener( FaultEvent.FAULT, faultHandler )
    hs.send();
    private function resultHandler( event:ResultEvent ):void
    arr = event.result.root.images.image as ArrayCollection;
    private function faultHandler( event:FaultEvent ):void
    Alert.show( "Fault Response from HTTPService call:\n " );
    ]]>
    </mx:Script>
    <mx:TileList id="tilelist"
    dataProvider="{arr}">
    <mx:itemRenderer>
    <mx:Component>
    <mx:Image source="images/{data}" />
    </mx:Component>
    </mx:itemRenderer>
    </mx:TileList>
    </mx:Application>

  • How to Copy an Image File from a Folder to another Folder

    i face the problem of copying an image file from a folder to another folder by coding. i not really know which method to use so i need some reference about it. hope to get reply soon, thx :)

    Try this code. Make an object of this class and call
    copyTo method.
    import java.io.*;
    import java.net.*;
    import java.util.*;
    public class FileUtil
    extends File {
    public FileUtil(String pathname) throws
    NullPointerException {
    super(pathname);
    public void copyTo(File dest) throws Exception {
    File parent = dest.getParentFile();
    parent.mkdirs();
    FileInputStream in = new FileInputStream(this); //
    Open the source file
    FileOutputStream out = new FileOutputStream(dest); //
    Open the destination file
    byte[] buffer = new byte[4096]; // Create an input
    buffer
    int bytes_read;
    while ( (bytes_read = in.read(buffer)) != -1) { //
    Keep reading until the end
    out.write(buffer, 0, bytes_read);
    in.close(); // Close the file
    out.close(); // Close the file
    This is poor object-oriented design. Use derivation only when you have to override methods -- this is just
    a static utility method hiding here.

  • Opening image file from Form 6i deployed on Application server

    Hi
    I am working on an applictaion where a form 6i is deployed on application server.The application reads an image file from hard disk.The form works fine when I run in form developer . But when I deploy on application server the form using get_file_name do not reads the image file.
    Please help
    Prashant

    Hi!
    In forms 10g we use webutil for that. I think forms 6i do not support that.
    May search here in the forum for webutil for 6i.
    Some guys had built a webutil.pll that s working on 6i.
    Here is the thread: Converting to Webutil? 6i and 9i equivalents.
    Regards
    Edited by: Magoo on 18.09.2009 11:10

  • Problem in reading Sql server data from text file.

    I am selecting record from sql server 2005 and save the result in text file.
    The text file contains , delimiter.
    I am reading same txt file from java & insert into database.
    But it shows "��S and box like characters along with original text.
    Regards
    Joe

    I also tried a lot for this. And didn't want to do copy paste for all .sql files. Finally the files could be read as is the clue is to read the file using UTF-16 format like
    BufferedReader br=new BufferedReader(new InputStreamReader(fis,Charset.forName("UTF-16")));
    I guess it would help and save work to copy paste text to other files and resaving it!

  • How to make a image file from Pre installed Mac osx ? "PLEASE HELP :("?

    hey guys ..Thanks u for the time.
    So i have this eMac which has crashed and i have got may hands on another eMac.. and it works
    ... the only problem is.. I can take my eMac to the working eMac to do Target Mode or any thing...
    So Help me..
    My question is .. Is there a way to make a .DMG image file from pre installed mac osx OR
    Is there a way to may a recovery disc??

    You can use Carbon Copy Cloner to copy everything from the working eMac onto the non-working eMac while the working eMac is running. If your eMac will still do target mode into the working one, you can download the above software, select the booted drive as the source drive, and your eMac's drive as the target, however it is possible this will not work.
    When you say your eMac crashed, what exactly happened?  It is possible that the hard drive in your eMac failed or is failing, so in order to get it running again you would need to replace the hard drive.  On the eMac, this repair is somewhat involved, and you have to be very careful because it exposes the CRT, which has several areas which can be extremely dangerous to touch if not properly handled.  CRTs retain a great deal of voltage, even when unplugged, sometimes for weeks, and they can give you a nasty shock if you touch them in the wrong place.
    Also keep in mind that cloning from the working computer to the non-working computer will ERASE any data that you have stored on that eMac, so if you don't have it backed up anywhere, you may want to attempt that with target mode before proceeding.
    Good luck!

  • How to Insert image file from fileChooser to a tabbedPane?

    Hi,
    Currently, i have encounted a problem halfway through my project. That is how do i insert images into a tabbedPane after selecting a image file from the fileChooser?
    Do anyone has any idea of how to solve the above problem?
    Thanks!!

    I would put the image in a JLabel and put the JLabel in the tabbed pane.

  • Loading PNG image file from Applet?

    Hi All,
    My applet running on IE6 and it will often loads 100 PNG image files from a webserver.
    Size of PNG file is about 60Kb so 100*60=6000 Kb ~ 6M.
    In theory, the applet will took 6M of memory to store all 100 files. In practical, it tooks about
    6M* 25 = 150M of memory, that make my applet run in out of memory sometimes.
    I know the reason, may be the brower/applet convert the PNG file format to BMP file format before showing on the screen.
    So the main point here is the applet should not loads all 100 files into the memory,
    it should loads only 10 files at the same time, another 90 files should be cached in memory as PNG file format, not BMP image file format to save the memory usage.
    Is this solution possible in applet field?
    If it is possible how can I implement it?
    And please show me better solution if anys.
    Many Thanks.

    I know the reason, may be the brower/applet convert the PNG file format to
    BMP file format before showing on the screen.This sounds VERY unlikely! Why should the browser do that? And the applet does what you have coded I hope!
    Your problem is probably somewhere else. And it has nothing to do with applets I presume. Use a heap analyzer tool to find out what hogs the memory. A thorough code review can't hurt either. If you still thinks it is the images though, then just don't load them all at once then.

  • Reading a image file and printing it by a Servlet

    In a IMAGE TAG of HTML file i am calling servlets what will write a image to the browser.
    <IMG SRC="http://localhost/WriteImage" width="50" height="100">
    The Servlet WriteImage has to read a image from a location(it could be gif,jpeg,png or another format of images ) and it has to write to the above image tag.
    Anyone can u help me out how i can do this...
    I tried out with javax.imageio package but couldn't get it.
    Thank Q
    Vijay

    Your WriteImage servlet needs to read the image file in from wherever it is (hard drive, database, whatever), then write it back out to the browser. To do that, first use the HTTPServletResponse object to send the appropriate headers, then call the getOutputStream() method to get an output stream to write the data to. This data will be sent to the browser which, if you've set the headers correctly, will display it as an image.
    It's been a long time since I did this (we abandoned storing images in databases quite a long time ago), so I can't be more specific than that, but hopefully that'll be enough to get you going. If you run into any problems, reply and I'll see if I can help further.

  • Signed Applet can't read an image file??

    Hi my dear java folks,
    I've written a simple applet and self-signed it in order to have access
    to local machine's files.
    The applet as you see needs to read an image file (arrow.gif).
    The applet is:
    import.....
    public class MyApplet extends JApplet{
    JButton button1=new JButton("Save");
    JButton button2=new JButton(new ImageIcon("arrow.gif"));
    public void init(){
    button1.setBounds(10,70,80,20);
    button2.setBounds(10,100,80,20);
    getContentPane().setLayout(null);
    getContentPane().add(button1);
    getContentPane().add(button2);
    The java.policy file is:
    keystore ".//myworkingstore.store";
    grant codeBase "http://fin2000/htdocs/MyApplet.class" {
    permission java.io.FilePermission "<<ALL FILES>>","read";
    permission java.io.AllPermission;
    grant codeBase "." signedBy "MyName" {
    permission java.io.FilePermission "${user.home}/*.*","read,write";
    permission java.io.FilePermission "<<ALL FILES>>","read";
    permission java.io.AllPermission;
    The java.security file is on the server
    (on my server I have Oracle8.1/Apache installed):
    policy.url.1=file:d:/oracle/ora81/apache/apache/htdocs/java.policy;
    My problem is when I run my applet through a html file
    "http://myServerName/test.html" in my browser, the applet
    runs correctly except it's button2 (the iconized button), the
    button comes without it's ImageIcon on it.
    I receive no errors, no messages and no signs of error
    I am completely confused!
    Need Urgent Help
    Thank you , Jamanir

    Hi,
    this has nothing to do with a security problem.
    Change you code as follow:
      JButton button2 = new JButton(new ImageIcon(getClass().getResource("arrow.gif")) ;Pack arrow.gif in the same directory/package as MyApplet.class in the jar file and It should solve your problem...
    The problem is that when you write new ImageIcon("arrow.gif"), it works locally as a standalone application, because "arrow.gif" is mapped to the current directory where you application is started from. This has no meaning when you works online with an applet. That's the reason why your graphic was not found.
    getClass().getResource("arrow.gif") returns an URL pointing to a file "arrow.gif" located at the same location as the class. This always works either locally or online, other packed in a Jar file, or unpacked.
    Yannick

  • How to remove image files from audio files

    i dont understand enough about how itunes worked...So my problem is, when i would add album art to a song, i would copy and past to the artwork box on the song. When i would find a better image, i would just past over the last one, not realizing that it was actually adding another image. This form of Copy/past(as i understand) saves the image to the audio file. *My question:* how do i remove the image files from the audio files...?

    Right click on the file you want to remove the artwork from, choose Get Info then the Artwork tab, click on the image and press the delete button then OK. To remove from multiple items, highlight the adjacent tracks in your selection (click on the first in the list, hold down the shift key and click on the last), right click and choose Get Info, choose yes when you are asked if you want to edit multiple items, tick the box beside the small empty artwork window about halfway down on the right. (if the songs aren't adjacent to each other but spread through out the playlist or library CTRL & Click on each of the songs you want to highlight)

  • How to display a dynamic image file from url?

    Hey,I want to display a dynamic image file from url in applet.For example,a jpg file which from one video camera server,store one frame pictur for ever.My java file looks like here:
    //PlayJpg.java:
    import java.awt.*;
    import java.applet.*;
    import java.net.*;
    public class PlayJpg extends Applet implements Runnable {
    public static void main(String args[]) {
    Frame F=new Frame("My Applet/Application Window");
    F.setSize(480, 240);
    PlayJpg A = new PlayJpg();
    F.add(A);
    A.start(); // Web browser calls start() automatically
    // A.init(); - we skip calling it this time
    // because it contains only Applet specific tasks.
    F.setVisible(true);
    Thread count = null;
    String urlStr = null;
    int sleepTime = 0;
    Image image = null;
    // called only for an applet - unless called explicitely by an appliaction
    public void init() {
                   sleepTime = Integer.parseInt(getParameter("refreshTime"));
              urlStr = getParameter("jpgFile");
    // called only for an applet - unless called explicitely by an appliaction
    public void start() {
    count=(new Thread(this));
    count.start();
    // called only for applet when the browser leaves the web page
    public void stop() {
    count=null;
    public void paint(Graphics g) {
    try{
    URL location=new URL(urlStr);
    image = getToolkit().getImage(location);
    }catch (MalformedURLException mue) {
                   showStatus (mue.toString());
              }catch(Exception e){
              System.out.println("Sorry. System Caught Exception in paint().");
              System.out.println("e.getMessage():" + e.getMessage());
              System.out.println("e.toString():" + e.toString());
              System.out.println("e.printStackTrace():" );
              e.printStackTrace();
    if (image!=null) g.drawImage(image,1,1,320,240,this);
    // called each time the display needs to be repainted
    public void run() {
    while (count==Thread.currentThread()) {
    try {
    Thread.currentThread().sleep(sleepTime*1000);
    } catch(Exception e) {}
    repaint(); // forces update of the screen
    // end of PlayJpg.java
    My Html file looks like here:
    <html>
    <applet code="PlayJpg.class" width=320 height=240>
    <param name=jpgFile value="http://Localhost/playjpg/snapshot0.jpg">
    <param name=refreshTime value="1">
    </applet>
    </html>
    I only get the first frame picture for ever by my html.But the jpg file is dynamic.
    Why?
    Can you help me?
    Thanks.
    Joe

    Hi,
    Add this line inside your run() method, right before your call to repaint():
    if (image != null) {image.flush();}Hope this helps,
    Kurt.

Maybe you are looking for

  • Does anyone know anything about U2 being downloaded for free to everyone with iTunes?

    I am wondering about my iTunes account, I heard a whole album was free to everybody with an iTunes account. I apparently got the whole album downloaded into my iTunes account without even realizing it, and it charged me money, so I'm wondering can I

  • Analog delay

    hi .. I have an analog signal (2.225Mhz) .. and I want to get it delayed by 0.2 ms Is there any idea ??? Thnx in advance

  • Need to remove work item.

    Hi Experts, I am getting a work item in SBWP Transaction.Now If I check the workflow for this ITem Through Transaction PFTC. I got in Rules there in responsibility tabs have no position which consists our user. But still the Our user is getting that

  • How do I sync an old I-pod with MP-3s to a new PC w different account?

    Long story short: My old PC that had the backups for the MP3s on it was stolen. I still have the I-Pod that has those MP3s. My wife and kids have another PC with a different I-tunes account. How do I sync that old I-Pod with their account and not los

  • Bugs in iOS 7.0.3

    Hi everyone, Do you have this bug whereby you pull down the notification centre and the background application also get pulled to the top of the page as well? I am reading my tweets where I pull down the notification centre, and at the same time, my