Версия для печати темы
Нажмите сюда для просмотра этой темы в оригинальном формате
Форум программистов > Java: Работа с сетью > Как сохранить картинку


Автор: Guest 4.4.2005, 18:02
Ребята ест картинка, находяшаяся на одном сайте. как мне ее скачат и сохранить в формат BMP и JPG?

Код

 Url="http://pic.autoscout24.de/images/9/2/4/46838429_2.jpg";
    URL hp = new URL(Url);
    System.out.println("Url= "+Url);
    URLConnection hpCon = hp.openConnection();
 hpCon.connect();
 int len = hpCon.getContentLength();
 if (len > 0) {


      bis = new BufferedInputStream(hpCon.getInputStream());
      //int i = len;
//      InputStream input = hpCon.getInputStream();
      while (((c = bis.read()) != -1) && (--len > 0)) {
        s2.append(c);
      }
      bis.close();
    }
    else {
      System.out.println("Net sodergimogo ili no connection");
    }

    FileWriter raf10 = new FileWriter("zwischen123.jpg");
    raf10.write(s2.toString());
    raf10.close();


Пробовал так не откривает.
smile

Автор: igon 5.4.2005, 02:21
Код

...
        BufferedOutputStream out = null;   // The output stream (for storing the contents of the file)
        BufferedInputStream  in  = null;   // The input stream (for reading the contents of the file
        URL                  url;
        HttpURLConnection    con;
        int                  block = 4096;          // размер буфера
        byte[]               buf = new byte[block]; // буфер ввода/вывода
        int                  count = 0;             // The number of bytes read in one iteration
        boolean              notEmpty;
            notEmpty = false;
            try
              {
                url = new URL("http://pic.autoscout24.de/images/9/2/4/46838429_2.jpg"); // Open a connection
                con = (HttpURLConnection)url.openConnection(); // Cast для HTTP протокола, для других должен быть другой
                count = 0;  // The number of bytes read in one iteration
                in = new BufferedInputStream(con.getInputStream()); // Получение входного потока
                    while((count = in.read(buf, 0, block)) != -1)
                      {
                            if (!notEmpty)
                              {
                                notEmpty = true;
                                out = new BufferedOutputStream(new FileOutputStream(OUT_FOLDER+fileIn)); // Output file
                              }
                      }
                   }
              }
              catch (FileNotFoundException e)
                {
                }
              catch (MalformedURLException e)
                {
                }
              catch (IOException e)
                {
                }
              finally
                {
                  if (out != null) 
                    { 
                      try {
                            out.close();
                          }  
                          catch (IOException e)
                            {
                            }

                    }
                  if (in != null) 
                    {
                      try {
                            in.close();
                          }  
                          catch (IOException e)
                            {
                            }

                    }
                } 
          }
      }
- "вырезка" из рабочей программы, м.б. вырезал слишком много smile

Автор: Guest 5.4.2005, 10:36
Если я етот код запускаю и ставлю вместо
Код

OUT_FOLDER+fileIn

и ставлю
Код

"123.jpg"


почему-то создается пустой файл

Автор: Гость_unkis 5.4.2005, 18:22
Ребята подскажите как всёже сохраить ресуок.

Автор: Domestic Cat 6.4.2005, 03:34
Код

ImageIO.write(image, "png", new File(outFileName));


http://java.sun.com/j2se/1.4.2/docs/api/javax/imageio/ImageIO.html

Автор: igon 6.4.2005, 07:54
Уппс, действительно "вырезал" лишнее, sorry!
Вот так работает:

Код

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import java.net.HttpURLConnection;
import java.net.MalformedURLException;
import java.net.URL;


public class DownLoadPicture
{  
  public  static final String          OUT_FOLDER = "C:\\Downloads\\";

  public static void main (String[] args)  
    {  
      doIt(); 
    }  
      
  public static void doIt()
    {  
      BufferedOutputStream out = null;   // The output stream (for storing the contents of the file)
      BufferedInputStream  in  = null;   // The input stream (for reading the contents of the file
      URL                  url;
      HttpURLConnection    con;
      int                  block = 4096;          // размер буфера
      byte[]               buf = new byte[block]; // буфер ввода/вывода
      int                  count = 0;             // The number of bytes read in one iteration
      boolean              notEmpty;
      notEmpty = false;
      try
        {
          url = new URL("http://pic.autoscout24.de/images/9/2/4/46838429_2.jpg"); // Open a connection
          con = (HttpURLConnection)url.openConnection(); // Cast для HTTP протокола, для других должен быть другой
          count = 0;  // The number of bytes read in one iteration
          in = new BufferedInputStream(con.getInputStream()); // Получение входного потока
          while((count = in.read(buf, 0, block)) != -1)
            {
              if (!notEmpty)
                {
                  notEmpty = true;
                  out = new BufferedOutputStream(new FileOutputStream(OUT_FOLDER+"123.jpg")); // Output file
                }
              out.write(buf, 0, count); // Вот здесь
            }
        }
        catch (FileNotFoundException e)
          {
          }
        catch (MalformedURLException e)
          {
          }
        catch (IOException e)
          {
          }
        finally
          {
            if (out != null) 
              { 
                try 
                  {
                    out.close();
                  }  
                  catch (IOException e)
                    {
                    }

              }
              if (in != null) 
                {
                  try 
                    {
                      in.close();
                    }  
                    catch (IOException e)
                      {
                      }
                }
          } 
    }
}

Powered by Invision Power Board (http://www.invisionboard.com)
© Invision Power Services (http://www.invisionpower.com)