Модераторы: LSD, AntonSaburov
  

Поиск:

Ответ в темуСоздание новой темы Создание опроса
> Как сохранить картинку 
:(
    Опции темы
Guest
  Дата 4.4.2005, 18:02 (ссылка)    |    (голосов: 0) Загрузка ... Загрузка ... Быстрая цитата Цитата


Unregistered











Ребята ест картинка, находяшаяся на одном сайте. как мне ее скачат и сохранить в формат 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 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 327
Регистрация: 30.10.2004

Репутация: 2
Всего: 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



--------------------
Хотите поговорить об этом?
PM   Вверх
Guest
Дата 5.4.2005, 10:36 (ссылка)    |    (голосов: 0) Загрузка ... Загрузка ... Быстрая цитата Цитата


Unregistered











Если я етот код запускаю и ставлю вместо
Код

OUT_FOLDER+fileIn

и ставлю
Код

"123.jpg"


почему-то создается пустой файл
  Вверх
Гость_unkis
Дата 5.4.2005, 18:22 (ссылка)    |    (голосов: 0) Загрузка ... Загрузка ... Быстрая цитата Цитата


Unregistered











Ребята подскажите как всёже сохраить ресуок.
  Вверх
Domestic Cat
Дата 6.4.2005, 03:34 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Эксперт
****


Профиль
Группа: Экс. модератор
Сообщений: 5452
Регистрация: 3.5.2004
Где: Dallas, US

Репутация: 1
Всего: 172



Код

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


http://java.sun.com/j2se/1.4.2/docs/api/ja...io/ImageIO.html


--------------------

PM   Вверх
igon
Дата 6.4.2005, 07:54 (ссылка) | (нет голосов) Загрузка ... Загрузка ... Быстрая цитата Цитата


Опытный
**


Профиль
Группа: Участник
Сообщений: 327
Регистрация: 30.10.2004

Репутация: 2
Всего: 21



Уппс, действительно "вырезал" лишнее, 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)
                      {
                      }
                }
          } 
    }
}



--------------------
Хотите поговорить об этом?
PM   Вверх
  
Ответ в темуСоздание новой темы Создание опроса
Правила форума "Java"
LSD   AntonSaburov
powerOn   tux
  • Прежде, чем задать вопрос, прочтите это!
  • Книги по Java собираются здесь.
  • Документация и ресурсы по Java находятся здесь.
  • Используйте теги [code=java][/code] для подсветки кода. Используйтe чекбокс "транслит", если у Вас нет русских шрифтов.
  • Помечайте свой вопрос как решённый, если на него получен ответ. Ссылка "Пометить как решённый" находится над первым постом.
  • Действия модераторов можно обсудить здесь.
  • FAQ раздела лежит здесь.

Если Вам помогли, и атмосфера форума Вам понравилась, то заходите к нам чаще! С уважением, LSD, AntonSaburov, powerOn, tux.

 
0 Пользователей читают эту тему (0 Гостей и 0 Скрытых Пользователей)
0 Пользователей:
« Предыдущая тема | Java: Работа с сетью | Следующая тема »


 




[ Время генерации скрипта: 0.0481 ]   [ Использовано запросов: 22 ]   [ GZIP включён ]


Реклама на сайте     Информационное спонсорство

 
По вопросам размещения рекламы пишите на vladimir(sobaka)vingrad.ru
Отказ от ответственности     Powered by Invision Power Board(R) 1.3 © 2003  IPS, Inc.