【Java】IO操作之以圖片地址下載圖片

來源:互聯網
上載者:User
文章目錄
  • 源碼下載:
以圖片地址下載圖片讀取給定圖片檔案的內容,用FileInputStream
public static byte[] mReaderPicture(String filePath) {byte[] arr = null;try {File file = new File(filePath);FileInputStream fReader = new FileInputStream(file);arr = new byte[1024*100];fReader.read(arr);} catch (Exception  e) {// TODO: handle exceptione.printStackTrace();}return arr;}

根據byte數組,建立一張新圖。

public static void mWriterPicture(String newFileName,byte[] b){try {File file = new File(newFileName);FileOutputStream fStream = new FileOutputStream(file);fStream.write(b);fStream.close();System.out.println("圖片建立成功    "+b.length);} catch (Exception e) {// TODO: handle exception}}

擷取指定網址的圖片,返回其byte[]

public static byte[] mReaderPictureToInternet(String strUr1){byte[] imgData = null;URL url;try {url = new URL(strUr1);URLConnection connection = url.openConnection();int length = (int)connection.getContentLength();InputStream is = connection.getInputStream();if (length!=-1) {imgData = new byte[length];byte[] temp = new byte[500*1024];int readLen = 0;int destPos = 0;while ((readLen = is.read(temp))>0) {System.arraycopy(temp, 0, imgData, destPos, readLen);//arraycopy(Object src, int srcPos, Object dest, int destPos, int length) //從指定源數組中複製一個數組,複製從指定的位置開始,到目標數組的指定位置結束destPos+=readLen;}}return imgData;} catch (Exception e) {// TODO Auto-generated catch blocke.printStackTrace();}return imgData;}

直接擷取指定網址的圖片

public static void DownPictureToInternet(String filePath,String strUr1){try {URL url = new URL(strUr1);InputStream fStream = url.openConnection().getInputStream();int b = 0;FileOutputStream fos = new FileOutputStream(new File(filePath));while ((b=fStream.read())!=-1) {fos.write(b);}fStream.close();fos.close();} catch (Exception e) {e.printStackTrace();}}

應用:

public static void main(String[] args) {mWriterPicture("test/1.jpg", mReaderPicture("res/me.jpg"));mWriterPicture("test/2.jpg", mReaderPictureToInternet("http://pic2.desk.chinaz.com/file/201209/7/qinghimingyue4_p.jpg"));DownPictureToInternet("test/下載.jpg","http://img3.100bt.com/upload/ttq/20130205/1360069663700.jpg");}
源碼下載:http://download.csdn.net/detail/oyuntaolianwu/5804447

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.