Java学习笔记——IO操作之以图片地址下载图片

以图片地址下载图片

读取给定图片文件的内容,用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 exception
			e.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 block
			e.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");
	}

源码下载:



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值