Imageicon created from byte array gives -1 height and -1 width...

Hi,
when I am trying to create an imageicon object from byte arrays the length and width of the object are coming to be -1.So I am unable to resize the image..
This is happening for only few images, most of them are working fine and I can resize it...
What possibly could be wrong??
ImageIcon imageIcon = new ImageIcon(pImageData) where pImageData is bytearray..
but I am getting imageIcon.getIconWidth()=-1
and
imageIcon.getIconHeight()=-1
Can anyone help???

es5f2000 wrote:
I'm not sure if this is related, but I believe that images which are not currently being rendered return -1, -1 as their size.It is not even correct, so I'm confident it is not related.
import java.awt.Image;
import javax.swing.ImageIcon;
import javax.imageio.ImageIO;
import java.net.URL;
class TestIconSize {
     public static void main(String[] args) throws Exception {
          Image image = ImageIO.read( new URL(
               "http://forums.sun.com/im/silver-star.gif") );
          ImageIcon imageIcon = new ImageIcon( image );
          System.out.println( "Width: " + imageIcon.getIconWidth() );
          System.out.println( "Height: " + imageIcon.getIconHeight() );
}Output.
andrew@pc1:/media/disk/projects/numbered/all$ java TestIconSize
Width: 16
Height: 16
andrew@pc1:/media/disk/projects/numbered/all$ The post after yours seems of even more dubious quality. For those (and other) reasons, I second Darryl's call for an SSCCE.

Similar Messages

  • Creating a byte Array dynamically.Urgent Help needed.

    Hi there,
    I need to create a byte Array with the values
    derived from the array and then am passing this byte array
    to a method.
    Example :
    public static void main(String[] args) throws IOException {
    char chars[] = {'a','j','a','y'};
    byte[] b = {
    (byte) chars[0],(byte) chars[1],(byte) chars[2],(byte) chars[3],
    //** Send name to a server.
    sendRequest(b);
    This is all right.
    But here I know the size of the character array chars.
    If it had more than 4 characters or less than 4,
    is there a way to create the byte array dynamically based on the values in the character array?
    Please can some one help me with creating a byte array on the fly?
    Has anyone understood my question please?
    A response is much much appreciated.

    The actual problem is this.
    The byte array already has some fixed values to it
    and i need to append the values of the character array
    to this byte array
    ie
    char chars[] = {'a','j','a','y'};
    byte b[] = {
    // Predefined values
    (byte) 0x01, (byte) 0x7E, (byte)0x03
    // I have to add the values from the array here
    (byte) chars[0], (byte) chars[1]....
    How can I add these values.? The size of the character array
    can vary

  • Creating a byte Array dynamically.An Urgent Request.

    Hi there,
    I need to create a byte Array with the values
    derived from the array and then am passing this byte array
    to a method.
    Example :
    public static void main(String[] args) throws IOException {
    char chars[] = {'a','j','a','y'};
    byte[] b = {
    (byte) chars[0],(byte) chars[1],(byte) chars[2],(byte) chars[3],
    //** Send name to a server.
    sendRequest(b);
    This is all right.
    But here I know the size of the character array chars.
    If it had more than 4 characters or less than 4,
    is there a way to create the byte array dynamically based on the values in the character array?
    Please can some one help me with creating a byte array on the fly?
    Has anyone understood my question please?

    Well, if you have the byte array already, you're probably going to have to either make the original array large enough to hold whatever you would put into it or create a new array when you know what you are going to add.
    This seems pretty simple, so maybe I'm missing the point. But...
    char chars[] = { ... };
    byte bytes[] = new byte[<some other size> + chars.length];
    for (int i = 0; i < chars.length; i++)
    bytes[i + <offset>] = (byte)chars;
    If you can't effectively figure out a static size for this array and you have to copy contents, look at System.arrayCopy() to possibly improve performance of the copy.

  • I have lost my pause button from keyboard please give me help and support immediately.

    HI,
          I have lost my pause button from keyboard please give me help and support immediately.  My contact number is 9803139305.

    Has iTunes been uninstalled or removed from you system?
    Is it no longer in the Start Menu or in Control Panel?
    What exactly was downloaded and installed?  There is no Windows 9, so it's not possible that it is installed on your computer.

  • Control the page height and page width of pdf report using pasta_pdf.cfg

    Hi All,
    I've followed the note: 338990.1 (how to print publisher PDF reports via the concurrent manager) in metalink to print a PDF REPORT. Everything work fine except the page height and page width is used as default (8X11). Is there anyway that i can custom page height and page width size such as: legal (8.5X14).
    current set up in pasta_pdf.cfg
    [DEFAULT]
    %% ============== Preprocessing Command ==================== %%
    % Pasta can use a preprocessing command to invoke any executable
    % that supports an input file and an output file (a filter program).
    % You can use redirection. Pasta will invoke the filter program
    % to preprocess the Pasta output before passing it to the printing
    % command. By using the preprocess option, you can generate output
    % formats other than the formats Pasta currently supports. For
    % example, you can generate PCL output.
    % You can use {infile} and {outfile} in this option.
    % {infile} is the output file generated by Pasta. You can use
    % it as input for the preprocessing command. It is a temporary
    % file and will be deleted after being passed to the
    % preprocessing command. {outfile} is the output file generated
    % by the preprocessing command. Pasta names it temporarily and
    % it will be deleted after being passed to the printing command.
    % If you want to keep it, you can name it by using the '-o'
    % command line option. Pasta will copy {outfile} to the file you
    % specify.
    % Preprocess for PDF output
    % This is an example for PDF output to print.
    ; Xpdf
    preprocess=/usr/local/bin/pdftops {infile} {outfile}
    ; Ghost Script
    ; preprocess=pdf2ps {infile} {outfile}
    ; Acrobat
    ; preprocess=acroread -toPostScript -pairs {infile} {outfile}
    %% ============== Printing Command ========================= %%
    % You can specify the printing command and options you want
    % to use to print your report. Pasta will pass the final output
    % to this command. {printername} will be replaced by the
    % actual printer name passed through the command line option
    % (-pn), so in most cases you don't have to change these
    % options.
    % for UNIX platform
    printCommand=lp -c -d{printername}
    % for Windows platform
    ntPrintCommand=print /D:{printername}
    %% ============== Error Log File =========================== %%
    % This tells Pasta to create a log file. The default error
    % output is stderr.
    ;errorlogfile=pasta.log
    NOTE: pasta version 3.0.4
    form server 6.0.8.27.0
    third party tool is pdftops
    Thanks
    Kevin

    i think that can be down from the printing direver/styles/prt files when you added the printer at your apps system check the follwoign for more info.
    ( How to Implement Printing for Oracle Applications: Getting Started )
    Note:269129.1
    (Step By Step Guide to Set Up a Printer in Oracle Applications)
    ( Note:60936.1)
    fadi
    http://oracle-magic.blogspot.com

  • Wpf/webbrowser:-how to get height,width,scroll height and scroll width of render html/xhtml/xml pages.

    hi I am using to web browser control to get  height,width,scroll height and scroll width in wpf c#.
    Could You please tell me how to achive this information if .pages contain this css on body.
     style="-webkit-column-width:800px;  margin-right:800px; -moz-column-width: 800px; column-width: 800px; -webkit-column-gap: 0px; -moz-column-gap: 0px; column-gap: 0px; -webkit-column-rule: 0px solid #000;-moz-column-rule: 0px solid #000;column-rule:
    0px solid #000; height:800px; overflow:visible !important; ; margin:0px; -moz-margin:0px;-webkit-margin:0px;display:block;"
    I have to get height,width,scroll height and scroll width  on on complete event.
    this is MainWindow.xaml page
    <Window x:Class="WPFWebBrowserInvokeScript.MainWindow"
            xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
            xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
            Title="MainWindow" Height="820" Width="820" Loaded="Window_Loaded">
        <Grid>
            <WebBrowser HorizontalAlignment="Left"
       Height="800"
       Margin="10,10,0,0"
       VerticalAlignment="Top"
       Width="800"
       Name="MainBrowser"/>
            <!--<Grid x:Name="grid1"></Grid>-->
        </Grid>
    </Window>
    this  MainWindow.xaml.cs
    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Windows;
    using System.Windows.Controls;
    using System.Windows.Data;
    using System.Windows.Documents;
    using System.Windows.Input;
    using System.Windows.Media;
    using System.Windows.Media.Imaging;
    using System.Windows.Navigation;
    using System.Windows.Shapes;
    using System.IO;
    namespace WPFWebBrowserInvokeScript
        /// <summary>
        /// Interaction logic for MainWindow.xaml
        /// </summary>
        public partial class MainWindow : Window
            public MainWindow()
                InitializeComponent();
            private void Window_Loaded(object sender, RoutedEventArgs e)
                string strHtml = "";
                using (StreamReader sr = new StreamReader("D:/epubunzip/ePub2_Sample03a_USgovernment_SE_Gr9-12_EN_U1/OPS/9780547451381_c01.html"))
                    strHtml = sr.ReadToEnd();
                    strHtml = strHtml.Replace("<body>", "<body  style=\"-webkit-column-width:800px; overflow:visible !important;  -moz-column-width: 800px; column-width: 800px; -webkit-column-gap:
    0px; -moz-column-gap: 0px; column-gap: 0px; -webkit-column-rule: 0px solid #000;-moz-column-rule: 0px solid #000;column-rule: 0px solid #000; height:800px; ; margin:0px; -moz-margin:0px;-webkit-margin:0px;display:block;\">");
                    string str = "<script> function execScript(){return document.body.scrollWidth;}</script></head>";
                    strHtml = strHtml.Replace("</head>", str);
                    byte[] bytes = Encoding.UTF8.GetBytes(strHtml);
                    MemoryStream ms = new MemoryStream();
                    ms.Write(bytes, 0, bytes.Length);
                    ms.Position = 0;
                    MainBrowser.NavigateToStream(ms);
                    //MainBrowser.NavigateToString(strHtml);
                    MainBrowser.LoadCompleted += new LoadCompletedEventHandler(MainBrowser_LoadCompleted);
            void MainBrowser_LoadCompleted(object sender, NavigationEventArgs e)
    //here I am trying to get  height,width,scroll height and scroll width
    //It's gtting wrong info
              WebBrowser webBrowser = (WebBrowser)sender;
                //mshtml.htmld webDocument = (mshtml.HTMLDDElement)webBrowser.Document;
                //mshtml.HTMLBody webBody = (mshtml.HTMLBody)webDocument;
                //    var dd = webDocument.InvokeScript("execScript");
                //    //  string script = "document.body.style.overflow ='hidden'";         
                //    // var dd = webDocument.InvokeScript("execScript", new Object[] { script, "JavaScript" });
                //    var elems = webBrowser.Document.GetElementsByTagName("body");
                //    System.Windows.Forms.HtmlElement webBody = (System.Windows.Forms.HtmlElement)webDocument.Body;
           

    >>if i am rendering html from MemoryStreamor string in webbrowser control in wpf It's not applying this css
    Yes it does. If you for example add background-color: yellow; to the stlyle you will see that the page turn yellow:
    strHtml = strHtml.Replace("<body>", "<body style=\"-webkit-column-width:800px; background-color: yellow; overflow:visible !important; -moz-column-width: 800px; column-width: 800px; -webkit-column-gap: 0px; -moz-column-gap: 0px; column-gap: 0px; -webkit-column-rule: 0px solid #000;-moz-column-rule: 0px solid #000;column-rule: 0px solid #000; height:800px; ; margin:0px; -moz-margin:0px;-webkit-margin:0px;display:block;\">");
    If the styles doen't get applied as expected it is a browser issue. The WebBrowser control emulates Internet Explorer in IE7 rendering mode by default.  You will have to change some registry settings to change this behaviour. Please refer to the following
    links for more information:
    http://weblog.west-wind.com/posts/2011/May/21/Web-Browser-Control-Specifying-the-IE-Version
    https://social.msdn.microsoft.com/Forums/vstudio/en-US/cf66e0cd-ab6f-45b8-b230-1d78f26670d2/opening-links-from-wpf-webbrowser-control-in-default-browser-instead-of-ie?forum=wpf
    -moz-column-width only works in FireFox for example.
    You may also navigate to an actual page and inject some javascript function that for example adds the styles to the body element dynamically or set the style properties of the body element directly:
    private void Window_Loaded(object sender, RoutedEventArgs e)
    MainBrowser.Navigate(@"E:/Epubs/ePub2_Sample05_Biology_SampleChapter_EN/OPS/ch01.xhtml");
    MainBrowser.LoadCompleted += new LoadCompletedEventHandler(webb_DocumentCompleted);
    private void webb_DocumentCompleted(object sender, NavigationEventArgs e)
    WebBrowser webBrowser = (WebBrowser)sender;
    dynamic doc = webBrowser.Document;
    //int _scrollWidth = (int)webBrowser.InvokeScript("execScript");
    //mshtml.HTMLDocument webDocument = (mshtml.HTMLDocument)webBrowser.Document;
    mshtml.HTMLScriptElement script = (mshtml.HTMLScriptElement)doc.createElement("script");
    script.setAttribute("type", "text/javascript");
    script.innerHTML = "function doSomething(){ /* do something here... */ }";
    //add script to the head
    dynamic head = doc.getElementsByTagName("head")[0];
    head.appendChild(script);
    mshtml.HTMLBody body = (mshtml.HTMLBody)doc.getElementsByTagName("body")[0];
    body.style.background = "yellow";
    //set any body.style property here...
    webBrowser.InvokeScript("doSomething");
    That's about it as far as WPF is concerned.
    Please remember to mark helpful posts as answer and/or helpful.

  • Report Row Height and Column Width

    Hi,
    I have a cell in a report (a description column) that causes the row height to become very large (when there is a lot of text in the description). I can make the column wider on the report attributes page, but there doesn't seem to be any place to influence the maximum height of a row on a report, short of modifying the template.
    Adding style attributes (e.g. max-height:30px) to an element only affects the <span> that the element resides in, not the table cell or row.
    Displaying the column as a text area is a useful workaround. The downside is the border and scroll bars do waste a lot of screen real estate. Does there exist some other way of setting a limit on the height and/or width of a report, report column or report row?
    Oh, and another question- how do make line breaks in this forum? There's no support for <BR> or [br].

    Please reply to this thread, my customer is facing the same issue. He does not have issue with the excel and the pdf output but in the rtf output the table heght increases to accomadate the data.He want it to bevave in the same way as the pdf do.
    Regards,
    Ajay

  • How to create PNG file from byte array of RGB value?

    Hi
    Here is my problem.
    I have drawn some sketchs (through code in runtime) on canvas. I have grabbed the RGB information for the drwan image and converted to byte array.
    I have to pass this byte array to server and generate a png file and save.
    Please help.

    {color:#ff0000}Cross posted{color}
    http://forum.java.sun.com/thread.jspa?threadID=5218093
    {color:#000080}Cross posting is rude.
    db{color}

  • Display image from byte array

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

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

  • Rendering screens from byte arrays

    If I have a very busy screen and somehow will find a way of creating that screen on the server will I be able to render that screen from a byte array (or something else) being sent from the server?
    Thanks

    No, I need a fully functional screen but somehow preprocessed thus FP won't need to do all the work but just paint it to the Stage. Probably a crazy idea.

  • How Do I Load An Animated GIF Into PictureBox Control From Byte Array?

    I'm having a problem with loading an animated GIF int a picturebox control in a C# program after it has been converted to a base64 string, then converted to a byte array, then written to binary, then converted to a base64 string again, then converted to
    a byte array, then loaded into a memory stream and finally into a picturebox control.
    Here's the step-by-step code I've written:
    1. First I open an animated GIF from a file and load it directly into a picturebox control. It animates just fine.
    2. Next I convert the image in the picturebox control (pbTitlePageImage) to a base64 string as shown in the code below:
                    if (pbTitlePageImage.Image != null)
                        string Image2BConverted;
                        using (Bitmap bm = new Bitmap(pbTitlePageImage.Image))
                            using (MemoryStream ms = new MemoryStream())
                                bm.Save(ms, ImageFormat.Jpeg);
                                Image2BConverted = Convert.ToBase64String(ms.ToArray());
                                GameInfo.TitlePageImage = Image2BConverted;
                                ms.Close();
                                GameInfo.TitlePageImagePresent = true;
                                ProjectNeedsSaving = true;
    3. Then I write the base64 string to a binary file using FileStream and BinaryWriter.
    4. Next I get the image from the binary file using FileStream and BinaryReader and assign it to a string variable. It is now a base64 string again.
    5. Next I load the base64 string into a byte array, then I load it into StreamReader and finally into the picturebox control (pbGameImages) as shown in the code below:
    byte[] TitlePageImageBuffer = Convert.FromBase64String(GameInfo.TitlePageImage);
                            MemoryStream memTitlePageImageStream = new MemoryStream(TitlePageImageBuffer, 0, TitlePageImageBuffer.Length);
                            memTitlePageImageStream.Write(TitlePageImageBuffer, 0, TitlePageImageBuffer.Length);
                            memTitlePageImageStream.Position = 0;
                            pbGameImages.Image = Image.FromStream(memTitlePageImageStream, true);
                            memTitlePageImageStream.Close();
                            memTitlePageImageStream = null;
                            TitlePageImageBuffer = null;
    This step-by-step will work with all image file types except animated GIFs (standard GIFs work fine). It looks like it's just taking one frame from the animation and loading it into the picturebox. I need to be able to load the entire animation. Does any of
    the code above cause the animation to be lost? Any ideas?

    There is an ImageAnimator so you may not need to use byte array instead.
    ImageAnimator.Animate Method
    http://msdn.microsoft.com/en-us/library/system.drawing.imageanimator.animate(v=vs.110).aspx
    chanmm
    chanmm

  • Make sound file from byte array?

    Ok say I have a program that gets a byte array from a sound file and then randomly removes some of the samples from the array, so that instead of having a value the bytes are just zeroes. I then want to play my new byte array. Here is the code I try to use but when I use it nothing happens.
    AudioFormat = ((AudioInputStream) AudioSystem.getAudioInputStream(**The Original Sound File**)).getFormat();
    int numBytesRead = 0;
    DataLine.Info dataLineInfo = new DataLine.Info(SourceDataLine.class, audioFormat);
    SourceDataLine sourceDataLineTemp = (SourceDataLine)AudioSystem.getLine(dataLineInfo);
    sourceDataLineTemp.write(audioArray, 0, audioArray.length);(Try..catch removed for clarity.)
    Also, is it possible to convert a byte array to a .wav sound file?

    Im pretty sure if you just write that byte array to disk and open it as a wav file that will do the trick, because thats all a wav file is anyways, a stream of bytes representing audio

  • How to make use of byte array to perform credit and debit in Wallet Applet

    Hi,
    Can anyone please explain me how to use the concept of byte arrays.. to perform credit and debit operations of a 6byte amount. Say for example.. the amount contains 3 bytes whole number, 1 byte decimal dot and 2 bytes fractional part.
    It would be helpful if anyone could post a code snippet.. that way i can undersatnd easily.
    Thanks in Advance
    Nara

    Hello
    as explained in the other topic, remember your high school years and how you leart to add numbers.
    then, reproduce these algorithms for base-256 numbers.
    fractional? just google about fixed point math and floating point math. The first one is easier, as they are managed as integers.
    example, you want to store 1,42€. Then you decide the real number to deal with is N*100, and you store 142. You get 2 decimal places of precision.
    in the computer world it's easier to store n*256 as it's just a byte shift.
    then the addition operations are the same, and you just interpret the values as fractional numbers.
    regards
    sebastien

  • 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

  • Creating a sound from an array of numeric values and playing it on speakers

    How do I create take a sound I have stored as an array (or could be an arraylist if needed) of numeric values (at the moment as doubles) whiten my program and output it to speakers? I am using blueJ.
    for example (0, 0.1, 0.4, 0.8, 0.9, 1, 0.8, 0.6, 0.3, 0.1, etc...) would be a very high frequency sin wave.
    Edited by: alan2here on Feb 6, 2008 11:28 AM

    I stumbled upon this thread with a question somewhat related:
    I've recorded a wave file from microphone. But what I would like is an array of numbers in the same way alan said. I'm also working on my own project involving signal processing (i'm trying to do speech recognition).
    I can't really find a nice way of getting that array of numbers. I've tried to find out how wave file stores it's data, and directly read from the File object, but i figured there should be an easier way...
    I used this code to read the sound:
    *     SimpleAudioRecorder.java
    *     This file is part of jsresources.org
    * Copyright (c) 1999 - 2003 by Matthias Pfisterer
    * All rights reserved.
    * Redistribution and use in source and binary forms, with or without
    * modification, are permitted provided that the following conditions
    * are met:
    * - Redistributions of source code must retain the above copyright notice,
    *   this list of conditions and the following disclaimer.
    * - Redistributions in binary form must reproduce the above copyright
    *   notice, this list of conditions and the following disclaimer in the
    *   documentation and/or other materials provided with the distribution.
    |<---            this code is formatted to fit into 80 columns             --->|
    import java.io.IOException;
    import java.io.File;
    import javax.sound.sampled.DataLine;
    import javax.sound.sampled.TargetDataLine;
    import javax.sound.sampled.AudioFormat;
    import javax.sound.sampled.AudioSystem;
    import javax.sound.sampled.AudioInputStream;
    import javax.sound.sampled.LineUnavailableException;
    import javax.sound.sampled.AudioFileFormat;
    public class SimpleAudioRecorder
    extends Thread
         private TargetDataLine          m_line;
         private AudioFileFormat.Type     m_targetType;
         private AudioInputStream     m_audioInputStream;
         private File               m_outputFile;
         public SimpleAudioRecorder(TargetDataLine line,
                             AudioFileFormat.Type targetType,
                             File file)
              m_line = line;
              m_audioInputStream = new AudioInputStream(line);
              m_targetType = targetType;
              m_outputFile = file;
         /** Starts the recording.
             To accomplish this, (i) the line is started and (ii) the
             thread is started.
         public void start()
              /* Starting the TargetDataLine. It tells the line that
                 we now want to read data from it. If this method
                 isn't called, we won't
                 be able to read data from the line at all.
              m_line.start();
              /* Starting the thread. This call results in the
                 method 'run()' (see below) being called. There, the
                 data is actually read from the line.
              super.start();
         /** Stops the recording.
             Note that stopping the thread explicitely is not necessary. Once
             no more data can be read from the TargetDataLine, no more data
             be read from our AudioInputStream. And if there is no more
             data from the AudioInputStream, the method 'AudioSystem.write()'
             (called in 'run()' returns. Returning from 'AudioSystem.write()'
             is followed by returning from 'run()', and thus, the thread
             is terminated automatically.
             It's not a good idea to call this method just 'stop()'
             because stop() is a (deprecated) method of the class 'Thread'.
             And we don't want to override this method.
         public void stopRecording()
              m_line.stop();
              m_line.close();
         /** Main working method.
             You may be surprised that here, just 'AudioSystem.write()' is
             called. But internally, it works like this: AudioSystem.write()
             contains a loop that is trying to read from the passed
             AudioInputStream. Since we have a special AudioInputStream
             that gets its data from a TargetDataLine, reading from the
             AudioInputStream leads to reading from the TargetDataLine. The
             data read this way is then written to the passed File. Before
             writing of audio data starts, a header is written according
             to the desired audio file type. Reading continues untill no
             more data can be read from the AudioInputStream. In our case,
             this happens if no more data can be read from the TargetDataLine.
             This, in turn, happens if the TargetDataLine is stopped or closed
             (which implies stopping). (Also see the comment above.) Then,
             the file is closed and 'AudioSystem.write()' returns.
         public void run()
                   try
                        AudioSystem.write(
                             m_audioInputStream,
                             m_targetType,
                             m_outputFile);
                   catch (IOException e)
                        e.printStackTrace();
         public static void main(String[] args)
              if (args.length != 1 || args[0].equals("-h"))
                   printUsageAndExit();
              /* We have made shure that there is only one command line
                 argument. This is taken as the filename of the soundfile
                 to store to.
              String     strFilename = args[0];
              File     outputFile = new File(strFilename);
              /* For simplicity, the audio data format used for recording
                 is hardcoded here. We use PCM 44.1 kHz, 16 bit signed,
                 stereo.
              AudioFormat     audioFormat = new AudioFormat(
                   AudioFormat.Encoding.PCM_SIGNED,
                   44100.0F, 16, 2, 4, 44100.0F, false);
              /* Now, we are trying to get a TargetDataLine. The
                 TargetDataLine is used later to read audio data from it.
                 If requesting the line was successful, we are opening
                 it (important!).
              DataLine.Info     info = new DataLine.Info(TargetDataLine.class, audioFormat);
              TargetDataLine     targetDataLine = null;
              try
                   targetDataLine = (TargetDataLine) AudioSystem.getLine(info);
                   targetDataLine.open(audioFormat);
              catch (LineUnavailableException e)
                   out("unable to get a recording line");
                   e.printStackTrace();
                   System.exit(1);
              /* Again for simplicity, we've hardcoded the audio file
                 type, too.
              AudioFileFormat.Type     targetType = AudioFileFormat.Type.WAVE;
              /* Now, we are creating an SimpleAudioRecorder object. It
                 contains the logic of starting and stopping the
                 recording, reading audio data from the TargetDataLine
                 and writing the data to a file.
              SimpleAudioRecorder     recorder = new SimpleAudioRecorder(
                   targetDataLine,
                   targetType,
                   outputFile);
              /* We are waiting for the user to press ENTER to
                 start the recording. (You might find it
                 inconvenient if recording starts immediately.)
              out("Press ENTER to start the recording.");
              try
                   System.in.read();
              catch (IOException e)
                   e.printStackTrace();
              /* Here, the recording is actually started.
              recorder.start();
              out("Recording...");
              /* And now, we are waiting again for the user to press ENTER,
                 this time to signal that the recording should be stopped.
              out("Press ENTER to stop the recording.");
              try
                   System.in.read();
              catch (IOException e)
                   e.printStackTrace();
              /* Here, the recording is actually stopped.
              recorder.stopRecording();
              out("Recording stopped.");
         private static void printUsageAndExit()
              out("SimpleAudioRecorder: usage:");
              out("\tjava SimpleAudioRecorder -h");
              out("\tjava SimpleAudioRecorder <audiofile>");
              System.exit(0);
         private static void out(String strMessage)
              System.out.println(strMessage);
    }Daniel

Maybe you are looking for