加载图片三种方式

这里用的是CIImage,同样可以转换成UIImage。内容比较简单,适合初学者。(自己忘记时看看,严禁商业转载)

//第一种,从应用程序包中(资源文件)加载图像

    NSString * path = [[NSBundle mainBundle] pathForResource:@"1" ofType:@"png"];

    NSURL * pathURL = [NSURL URLWithString:path];

    CIImage * img = [CIImage imageWithContentsOfURL:pathURL];

    

    

//    NSData * data = [[NSData alloc] initWithContentsOfFile:path];

//    CIImage * img = [CIImage imageWithData:data];

//    CIImage * img = [[CIImage alloc] initWithData:data];

    

    //第二种,从应用程序沙箱目录中的Document目录下获取图片

    NSArray * paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

    NSString * pathString = [[paths lastObject] stringByAppendingPathComponent:@"1.png"];

     NSURL * url = [NSURL URLWithString:pathString];

    CIImage * image = [CIImage imageWithContentsOfURL:url];

    //也可以转换成NSDate获取

    

    //第三种,从服务器端获取

    NSURL * uro = [NSURL URLWithString:@"http://*****/1.png"];

    //如果导入了SDWebImage框架,则可以直接根据url地址加载

    //没有第三方框架的情况下

    NSData * data = [NSData dataWithContentsOfURL:uro];

    CIImage * imag = [[CIImage alloc] initWithData:data];




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Unity中加载外部图片方式有很多种,最常用的方式包括: 1. 使用WWW类加载外部图片 这种方式比较简单,可以通过WWW类加载外部图片并将其转换为Texture2D对象。代码示例如下: ```c# IEnumerator LoadImage(string url) { // 创建一个新的WWW对象来加载图片 WWW www = new WWW(url); yield return www; // 如果图片加载成功,则创建一个新的Texture2D对象并将图片数据复制到这个对象中 if (www.error == null) { Texture2D texture = new Texture2D(www.texture.width, www.texture.height); www.LoadImageIntoTexture(texture); } else { Debug.LogError("Failed to load image from " + url + ": " + www.error); } } ``` 2. 使用UnityWebRequest加载外部图片 UnityWebRequest是Unity新推出的网络请求API,功能更为强大,支持多种网络请求方式,包括HTTP、HTTPS、FTP等。使用UnityWebRequest加载外部图片的代码示例如下: ```c# IEnumerator LoadImage(string url) { // 创建一个新的UnityWebRequest对象来加载图片 UnityWebRequest request = UnityWebRequestTexture.GetTexture(url); yield return request.SendWebRequest(); // 如果图片加载成功,则获取Texture2D对象 if (!request.isNetworkError && !request.isHttpError) { Texture2D texture = ((DownloadHandlerTexture)request.downloadHandler).texture; } else { Debug.LogError("Failed to load image from " + url + ": " + request.error); } } ``` 3. 使用AssetBundle加载外部图片 如果你需要频繁加载大量的图片资源,那么可以考虑使用AssetBundle来管理和加载这些资源。具体的做法是将图片打包成AssetBundle,并在需要使用时通过AssetBundle.LoadAsset()方法来加载。代码示例如下: ```c# IEnumerator LoadImage(string url) { // 创建一个新的AssetBundle对象来加载图片 AssetBundle bundle = AssetBundle.LoadFromFile(url); // 如果AssetBundle加载成功,则获取Texture2D对象 if (bundle != null) { Texture2D texture = bundle.LoadAsset<Texture2D>("image"); } else { Debug.LogError("Failed to load image from " + url); } } ``` 以上三种方式都可以加载外部图片,选择哪种方式取决于你的具体需求。如果只需要加载少量的图片资源,可以使用第一种或第二种方式;如果需要频繁加载大量的图片资源,可以考虑使用AssetBundle来管理这些资源。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值