-
2020-10-31 00:52:26
URL获取网络图片
import java.io.IOException; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; /** * 获取网络图片流 * * @param url * @return */ public InputStream getImageStream(String url) { try { HttpURLConnection connection = (HttpURLConnection) new URL(url).openConnection(); connection.setReadTimeout(5000); connection.setConnectTimeout(5000); connection.setRequestMethod("GET"); if (connection.getResponseCode() == HttpURLConnection.HTTP_OK) { InputStream inputStream = connection.getInputStream(); return inputStream; } } catch (IOException e) { System.out.println("获取网络图片出现异常,图片路径为:" + url); e.printStackTrace(); } return null; }
传入的URL必须是以
http://
开头的,因为我们使用了HttpURLConnection
更多相关内容 -
IOS 获取网络图片的大小
2014-05-19 11:05:42IOS 获取网络图片的大小 URL Image Size -
android安卓通过url获取网络图片并显示在imageview中
2013-12-18 18:14:30通过图片的url获取到图片,并显示到imageview中,本实例中选择的图片的百度官网的logo。仅提供一种获取网络图片的方法。 -
Android获取网络图片的宽高
2020-02-09 16:07:35有时我们需要在加载显示网络图片前拿到图片的宽高对控件做些处理,比如针对过长的图片只显示部分,点击后在展示全图,那么怎样拿到网络图片的宽高呢? 方式一、使用HttpURLConnection +BitmapFactory.Options 通过...有时我们需要在加载显示网络图片前拿到图片的宽高对控件做些处理,比如针对过长的图片只显示部分,点击后在展示全图,那么怎样拿到网络图片的宽高呢?
方式一、使用HttpURLConnection + BitmapFactory.Options
通过使用BitmapFactory.Options只解码边界的方式,避免将整个图片资源加载到内存而导致获取过多图片宽高时造成OOM
public static void getPicSize(String url, onPicListener listener) { mPicFixThreadPool.execute(() -> { HttpURLConnection connection; try { connection = (HttpURLConnection) new URL(url).openConnection(); InputStream inputStream = connection.getInputStream(); int[] imageSize = getImageSize(inputStream); mMainHandler.post(() -> listener.onImageSize(imageSize[0], imageSize[1])); inputStream.close(); } catch (IOException e) { e.printStackTrace(); } }); } private static int[] getImageSize(InputStream is) { BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; BitmapFactory.decodeStream(is, null, options); int[] size = new int[2]; size[0] = options.outWidth; size[1] = options.outHeight; LogUtil.i("--------------------width = " + size[0] + ",height = " + size[1]+"--------------------"); return size; } public interface onPicListener { void onImageSize(int width, int height); }
方式二、使用Glide
Glide.with(mContext).asBitmap().load(url).into(object : BitmapImageViewTarget(imageView) { override fun onResourceReady(resource: Bitmap, transition: Transition<in Bitmap>?) { super.onResourceReady(resource, transition) val width = resource.width val height = resource.height Log.i("kkk", "width = $width,height = $height") } })
方式三
待添加...
-
IOS开发笔记(十二)——SDWebImage获取网络图片,好友聊天发送图片功能
2019-06-02 22:57:02使用SDWebImage获取网络图片 好友聊天发送图片功能 三、实验结果 1.SDWebImage获取图片 首先利用cocoapod安装第三方工具SDWebImage 运行命令即可 pod install 在所需要的文件中import相关的库文件 #import ...中山大学数据科学与计算机学院本科生实验报告
(2019年春季学期)
一、实验题目
IM聊天工具
二、实现内容
- 使用SDWebImage获取网络图片
- 好友聊天发送图片功能
三、实验结果
1.SDWebImage获取图片
首先利用cocoapod安装第三方工具SDWebImage
运行命令即可
pod install
在所需要的文件中import相关的库文件
#import "UIImageView+WebCache.h"
简单的使用方法
// 根据url来加载imageView 图片缓存 [self.image sd_setImageWithURL:imageUrl];
其中image是UIImageView类型
其中imageUrl是NSURL类型,注意不是NSString,需要转换
[NSURL URLWithString:imagePath]
添加完成后的函数
// 这里需要使用block 可以在图片加载完成之后做些事情 [self.image2 sd_setImageWithURL:imagePath2 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { NSLog(@"这里可以在图片加载完成之后做些事情"); }];
添加默认图片
一是可以等待图片从云端加载回来再改变,二是避免网络访问错误的时候图片加载为空的情况。
// 给一张默认图片,先使用默认图片,当图片加载完成后再替换 [self.image1 sd_setImageWithURL:imagePath1 placeholderImage:[UIImage imageNamed:@"default"]];
具体使用例子
需求:IM聊天工具在用户登陆后会去服务器请求用户的信息,其中就包括用户的头像信息。我们的IM服务器会返回头像图片的url,这时需要客户端在加载的时候更新头像显示图片。
获取图片的url
// 获取用户的信息 -(void) getInfo{ AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; NSString *url = [URLHelper getURLwithPath:@"/account/info"]; [manager GET:url parameters:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nullable responseObject) { NSLog(@"getInfo success"); self.loginUser = [[UserModel alloc] initWithProperties:responseObject[@"data"][@"Username"] NickName:responseObject[@"data"][@"Nickname"] RemarkName:responseObject[@"data"][@"Username"] Gender:responseObject[@"data"][@"Gender"] Birthplace:responseObject[@"data"][@"Region"] // 这里就是头像的url ProfilePicture:responseObject[@"data"][@"Avatar"]]; NSLog(responseObject[@"data"][@"Avatar"]); [[DatabaseHelper getInstance] registerNewMessagesListener]; [self.socket SRWebSocketOpen]; } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) { NSLog(@"getInfo fail"); NSLog(@"%@", error.localizedDescription); }]; }
根据url来加载网络图片
// 使用SDWebImage第三方库加载网络图片,先设置默认头像等待网络请求 // step 1 : 定义UIImageView UIImageView *imgV = [[UIImageView alloc]init]; // step 2 : 获取url的string后缀 NSString *imagePath = [SERVER_DOMAIN stringByAppendingString:self.User.ProfilePicture]; // step 3 :拼接字符串并转换为url类型 [imgV sd_setImageWithURL:[NSURL URLWithString:imagePath] // step 4 :设置默认图片,在本地的一张图片 placeholderImage:[UIImage imageNamed:@"peppa"] // step 5 :加载完成后的函数,输出错误方便我们debug completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, NSURL *imageURL) { NSLog(@"error== %@",error); }];
实验效果:
2. 好友聊天发送图片功能
聊天工具离不开图片的发送,这里根据服务器api接口来实现好友之间发送图片的需求。
这里的接口需要上传图片,用到上一周已经实现了的multipart上传。还需要添加时间戳与发送用户的id两个参数在body中。
首先要在聊天界面添加发送图片的按钮
self.imageButton = [UIButton buttonWithType:UIButtonTypeContactAdd]; self.imageButton.frame = CGRectMake(SCREEN_WIDTH - 65, SCREEN_HEIGHT - 45, 40, 40); [self addSubview:self.imageButton]; // 添加点击事件:从图库中选择一张图片 // 选择图片 - (void)chooseImage:(UIButton *)btn { [self alterHeadPortrait]; } - (void)alterHeadPortrait{ PHAuthorizationStatus status = [PHPhotoLibrary authorizationStatus]; // 判断授权情况 if (status == PHAuthorizationStatusRestricted || status == PHAuthorizationStatusDenied) { // 无权限 NSLog(@"no auth"); } else{ NSLog(@"has auth!!!!!"); } //初始化提示框 UIAlertController *alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet]; //按钮:从相册选择,类型:UIAlertActionStyleDefault [alert addAction:[UIAlertAction actionWithTitle:@"从相册选择" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { //初始化UIImagePickerController UIImagePickerController *PickerImage = [[UIImagePickerController alloc]init]; //获取方式1:通过相册(呈现全部相册),UIImagePickerControllerSourceTypePhotoLibrary PickerImage.sourceType = UIImagePickerControllerSourceTypePhotoLibrary; //允许编辑,即放大裁剪 PickerImage.allowsEditing = YES; //自代理 PickerImage.delegate = self; //页面跳转 [self presentViewController:PickerImage animated:YES completion:nil]; }]]; //按钮:取消,类型:UIAlertActionStyleCancel [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]]; [self presentViewController:alert animated:YES completion:nil]; }
设置回调函数
获取完图片后,下一步需要将这个图片上传到服务器,这里调用sendImage函数,实现在下面说明
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary<NSString *,id> *) info{ //定义一个newPhoto,用来存放我们选择的图片。 UIImage *newPhoto = [info objectForKey:@"UIImagePickerControllerEditedImage"]; // NSLog(urlStr); [self dismissViewControllerAnimated:YES completion:nil]; UIImageView *imageView = [[UIImageView alloc] initWithImage:newPhoto]; // 上传到云端 [[UserManager getInstance] sendImage:@"/content/image" withImage:newPhoto withToUser:self.chatUser.UserID withDate:[NSDate date]]; }
上传图片给好友,与服务器交互
四个参数
- 后台接口api字段
- 图片 UImage类型
- 用户名 NSString类型
- 时间戳 NSDate类型
// 发送图片给好友 -(void) sendImage:(NSString* )path withImage:(UIImage* )image withToUser:(NSString* )userName withDate:(NSDate* )timestamp { AFHTTPSessionManager *manager = [AFHTTPSessionManager manager]; [manager.requestSerializer setValue:@"multipart/form-data" forHTTPHeaderField:@"Content-Type"]; // 处理url NSString* urlString = [URLHelper getURLwithPath:path]; NSLog(@"%@", urlString); // 添加参数 NSDictionary* params = @{@"to":userName, @"timestamp":timestamp}; // 发送图片 [manager POST:urlString parameters:params constructingBodyWithBlock: ^(id<AFMultipartFormData> _Nonnull formData){ // 图片转data NSData *data = UIImagePNGRepresentation(image); [formData appendPartWithFileData :data name:@"file" fileName:@"928-1.png" mimeType:@"multipart/form-data"]; } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id _Nonnull responseObject){ NSLog(responseObject[@"msg"]); } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error){ NSLog(@"sendImage fail"); NSLog(@"%@", error.localizedDescription); }]; }
这个与上周的头像图片上传,主要区别是多了一个body的参数,可以在post方法中添加参数即可,若仅需上传图片,则参数填为nil。
四、实验思考及感想
这周首先我主要是使用SDWebImage这个第三方库来完成对网络图片的显示,使用这个库可以方便的加载存储头像这类多次使用的图片,避免加载过于频繁。接着又实现了服务器的另一个接口的交互,完成好友间发送图片的需求。下一步就是如何将发送图片显示在聊天窗口中,之前是利用tableview来显示纯文字,故需要进行修改才能满足图片与文字间隔显示的需求,这个问题留待下周。
-
Android获取网络图片并显示的方法
2019-07-23 15:42:02本文实例为大家分享了Android获取网络图片并显示的具体代码,供大家参考,具体内容如下 使用 HttpURLConnection 获得连接,再使用 InputStream 获得图片的数据流,通过 BitmapFactory 将数据流转换为 Bitmap,再将 ...本文实例为大家分享了Android获取网络图片并显示的具体代码,供大家参考,具体内容如下
使用 HttpURLConnection 获得连接,再使用 InputStream 获得图片的数据流,通过 BitmapFactory 将数据流转换为 Bitmap,再将 Bitmap 通过线程的 Message 发送出去,Handler 接收到消息就会通知 ImageView 显示出来。
记得要在manifest文件中添加 < uses-permission android:name=”android.permission.INTERNET” />上网权限,不然无法显示图片。
工程文件结构:
布局文件中就一个 ImageView 用来显示图片,一个 Button 用来获取图片。
MainActivity.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
public class MainActivity extends AppCompatActivity {
Button button;
ImageView imageView;
String url = "http://i4.buimg.com/dccba6282641a9e0.jpg";
//String textURL = "http://192.168.1.104:8080/add.jsp";
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
button = (Button) findViewById(R.id.button);
imageView = (ImageView) findViewById(R.id.imageView);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
new Thread(new Runnable() {
@Override
public void run() {
Bitmap bmp = getURLimage(url);
Message msg = new Message();
msg.what = 0;
msg.obj = bmp;
System.out.println("000");
handle.sendMessage(msg);
}
}).start();
}
});
}
//在消息队列中实现对控件的更改
private Handler handle = new Handler() {
public void handleMessage(Message msg) {
switch (msg.what) {
case 0:
System.out.println("111");
Bitmap bmp=(Bitmap)msg.obj;
imageView.setImageBitmap(bmp);
break;
}
};
};
//加载图片
public Bitmap getURLimage(String url) {
Bitmap bmp = null;
try {
URL myurl = new URL(url);
// 获得连接
HttpURLConnection conn = (HttpURLConnection) myurl.openConnection();
conn.setConnectTimeout(6000);//设置超时
conn.setDoInput(true);
conn.setUseCaches(false);//不缓存
conn.connect();
InputStream is = conn.getInputStream();//获得图片的数据流
bmp = BitmapFactory.decodeStream(is);//读取图像数据
//读取文本数据
//byte[] buffer = new byte[100];
//inputStream.read(buffer);
//text = new String(buffer);
is.close();
} catch (Exception e) {
e.printStackTrace();
}
return bmp;
}
}
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。
-
java获取网络图片的宽和高
2018-09-12 11:03:21/** * 获取网络图片的宽和高 * @param url * @return */ public static String getWidthAndHeight(String url) { try { InputStream is = new URL(url).openStream(); ... -
android HttpClient 获取网络图片
2014-12-16 20:12:35android HttpClient 获取网络图片 实例 -
Android获取网络图片尺寸(宽高)
2019-03-09 15:44:35项目常有获取服务端图片的需求,自己做了下整理,希望帮助的大家和自己! /** * 获取服务器上的图片尺寸 */ public static int[] getImgWH(String urls) throws Exception { URL url = new URL(urls); ... -
Android获取网络图片的三种方法
2016-05-06 21:23:33Android获取网络图片 AsynTask异步获取 -
Android通过网络URL获取图片并显示
2017-03-18 17:19:36Android通过网络URL获取图片并显示 -
iOS 获取网络图片的尺寸
2017-05-25 10:27:16// 1、直接获取 NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:serverUrl]]; UIImage *showimage = [UIImage imageWithData:data]; DDLOG(@"w = %f,h = %f",showimage.size.width, -
Glide获取网络图片和本地图片的宽高
2018-11-26 15:35:54今天分享下Glide加载图片的番外篇,获取图片的宽高; 如果是本地图片的话,我们可以用BitmapFactory获取到图片的宽高,下面上代码 public static int getImageWidth(String pathUrl) { BitmapFactory.Options ... -
Json解析获取网络图片
2013-01-14 14:54:14本程序实现解析网络图片,并显示在android手机上。 -
Glide获取网络图片宽和高
2017-10-30 21:39:49glide 获取在线网络图片的宽和高。String url = "http://or4824vcd.bkt.clouddn.com/pexels-photo-236960.jpeg";Glide.with(getApplicationContext()) .load(url) .asBitmap()// -
python 获取网络图片的大小
2018-03-11 00:16:44#!/usr/bin/env python#encoding=utf-8import cStringIO, urllib2, Imageurl = 'http://www.jb51.net/images/logo.gif'file = urllib2.urlopen(url)tmpIm = cStringIO.StringIO(file.read())im = Image.open(tmpIm)p... -
获取网络图片的尺寸大小
2014-12-20 11:14:21但是对于网络图片来说,要想通过最优的方法获得尺寸就略微有点困难,大体思路有这么几种: 1.通过服务器处理。即在下行图片路径时拼接该图片的宽高。这种方法最简单,避免了不必要的网络请求,只需要从URL中截取... -
通过HttpURLConnection获取网络图片实例
2016-07-16 21:07:47今天主要介绍一下通过HttpURLConnection获取网络图片。通过点击button来获取图片内容。 → 布局文件: xmlns:tools="http://schemas.android.com/tools" an -
iOS 获取网络图片的宽高
2016-11-23 17:32:19iOS 获取网络图片的宽高 -
curl获取网络图片显示的问题
2017-12-21 03:48:16php网页中使用header('Content-type:image/JPEG')无效,因为我是要在已有的网页中显示,在设置...所以现在还是只能输出一堆二进制的图片。 我不想保存到本地之后再读取,想直接用图片网址就读取了,请问怎么解决? -
android 如何从网络获取一张图片并显示
2012-08-23 00:57:22如何从网络中获取一张图片,并显示出来?? 首先应想到若要从网络资源中获取图片,就需要通过流操作,于是就想到如何创建流。 第一步:指定图片资源的URL 第二步:通过RUL获取一个connection 第三步:通过连接获取... -
IOS开发 SDWebImage获取网络图片的尺寸
2017-09-15 11:07:24IOS开发获取网络图片的实际尺寸 -
android获取网络图片
2012-02-07 21:39:47自己写的android获取网络图片的小例子,代码通俗易懂很适合初学者。 -
c#获取网络图片 Image和byte[]数组的相互转换
2016-08-23 21:25:14获取网络图片并显示在picturbox上: private void getWebPicture_Click(object sender, EventArgs e) { WebRequest request = WebRequest.Create("http://d.hiphotos.baidu.com/image/h%3D200/sign=6008 -
Android中如何根据图片url路径来获取网络图片
2017-01-07 19:26:39原文地址:Android中如何根据图片url路径来获取网络图片 1、根据图片的URL路径来获取网络图片,核心代码如下: public static Bitmap getBitmap(String path) throws IOException{ URL url = new URL(path); ... -
java BufferedImage获取网络图片高度、宽度
2018-12-04 17:32:59java BufferedImage获取网络图片高度、宽度 import java.awt.image.BufferedImage; import java.io.IOException; import java.io.InputStream; import java.net.MalformedURLException; import java.net.URL; ... -
PHP 获取网络图片资源并保存
2018-09-29 10:56:22在进行后台图片资源整合时,我发现有需要获取网络图片的需要,简单的要求就是,先获取某个资源图片,然后由代 PHP 代码实现剪切水印等操作,最后进行上传服务器… ☺.框架 : ThinkPHP3.2.3 (越来越不想玩这个低... -
swift中获取网络图片
2015-12-24 15:36:42当你给的图片地址是一个URL时,你需要显示出来就需要去转换编码不然就不能显示的:如下所示 给定的图片地址是一个字符串类型的,所以需要转换为URL如下所示: let urlStr = NSURL(string: ... -
从网络获取图片按图片原大小显示
2012-08-01 16:25:35找了很多按原大小显示图片都没找到 无意中自己发现的 原来如此简单 分享一下