---
title: "NSURL转NSData转UIImage"
author: "zcw_java"
date: "2013-07-01T15:37:22Z"
tags: []
categories: ["移动开发"]
slug: "nsurl-nsdata-uiimage"
draft: false
lastmod: "2013-08-05T11:21:01Z"
id: 1896978
url: "https://zcw-java.iteye.com/blog/1896978"
---

```c++

NSAutoreleasePool *pool = [[nsautoreleasepool alloc] init];
        
            NSString *fileURL = [nsstring stringwithformat:@"http://%@/image/%@/show.jpg?n=%d", 1,1];
            NSData *dateImg = [nsdata datawithcontentsofurl:[nsurl urlwithstring:fileurl]];
            
            dispatch_sync(dispatch_get_main_queue(), ^{
                m_imgViewVideo.image = [uiimage imagewithdata:dateimg];
                
                if (![abservices bispreview])
                {
                    m_nPreviewCount = 0;
                }
            });
[pool drain];

```

dispatch_sync：提交块对象给指定的调剂队列，同步履行。
dispatch_async：提交块对象给指定的调剂队列，异步履行。

dispatch_async() 调用以后立即返回，dispatch_sync() 调用以后等到block执行完以后才返回，dispatch_sync()会阻塞当前线程。 


//访问图片时响应404的没获取到数据时，判断code，0为ok
NSString *strURL = ,strSubClass];
                NSError *error = nil;
                NSData *dataImg =  options:NSDataReadingMappedIfSafe error:&error];
                if ( == 0)
                {
                    //截取图片压缩
                    UIImage *imgCompress =  centerInSize:CGSizeMake(140, 140)];
                    NSData *dataCompress = UIImageJPEGRepresentation(imgCompress, 1.0);
                    
                    ;
                }

以下是在tableview中全部代码

```c++

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"cate_cell";
    
    CateTableCell *cell = [tableview dequeuereusablecellwithidentifier:cellidentifier];
    
    if (cell == nil)
    {
        cell = [[[catetablecell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                     reuseIdentifier:CellIdentifier] autorelease];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    //cell默认图片
    UIImageView *imgDefault = [[uiimageview alloc] init];
    imgDefault.image = [self image:[uiimage imagenamed:@"alarm_icon.png"] centerInSize:CGSizeMake(140, 140)];
    
    //获取每条报警记录
    NSDictionary *cate = [m_mutarralarmpiclist objectatindex:indexpath.row];
    NSString *strImgPath = [nsstring stringwithformat:@"%@_0.jpg",[cate objectforkey:@"alarmpic"]];
    
    //搜索缓存
    UIImage *image = [self searchcacheimg:strimgpath ncellindexpath:indexpath.row];
    if(image != nil)
    {
        imgDefault.image = image;
    }
    else
    {
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            
            NSString *strURL = [nsstring stringwithformat:kurlreadcameraalarminfo,[abservices currentusername],strImgPath];
            NSError *error = nil;
            NSData *dataImg = [nsdata datawithcontentsofurl:[nsurl urlwithstring:strurl] options:NSDataReadingMappedIfSafe error:&error];
            if ([error code] == 0)
            {
                //截取图片压缩
                UIImage *imgCompress = [self image:[uiimage imagewithdata:dataimg] centerInSize:CGSizeMake(140, 140)];
                NSData *dataCompress = UIImageJPEGRepresentation(imgCompress, 1.0);
                
                [self saveimage:datacompress nindex:indexpath.row picname:strimgpath];
                dispatch_sync(dispatch_get_main_queue(), ^{
                    imgDefault.image = [uiimage imagewithdata:datacompress];
                    NSArray *arrRows = [nsarray arraywithobjects:indexpath, nil];
                    [_tableview reloadrowsatindexpaths:arrrows withrowanimation:uitableviewrowanimationnone];
                });
            }
            
        });
    }
    cell.logo.image = imgDefault.image;
    [imgdefault release];
    cell.title.text = [self stringformatdate:[cate objectforkey:@"alarmpic"]];
    
    cell.subTtile.text = [nsstring stringwithformat:@"%@",[cate objectforkey:@"alarmsensor"]];
    
    return cell;
}

```


```c++

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    SubCateViewController *subVc = [[[subcateviewcontroller alloc]
                                     initWithNibName:NSStringFromClass([subcateviewcontroller class])
                                     bundle:nil] autorelease];
    NSDictionary *cate = [m_mutarralarmpiclist objectatindex:indexpath.row];
    subVc.m_nIndexPathRow = indexPath.row;
    
    //保存选中cell索引
    m_nSelectedCellIndex = indexPath.row;
    
    NSMutableArray *mutArrPics = [[nsmutablearray alloc] init];
    for (int i=0; i < 10; i++)
    {
        NSString *strSubClass = [nsstring stringwithformat:@"%@_%d.jpg",[cate objectforkey:@"alarmpic"],i];
        [mutarrpics addobject:strsubclass];
        dispatch_async(dispatch_get_global_queue(0, 0), ^{
            //搜索图片是否存在
            UIImage *image = [self searchcacheimg:strsubclass ncellindexpath:indexpath.row];
            if(image == nil)
            {
                NSString *strURL = [nsstring stringwithformat:kurlreadcameraalarminfo,[abservices currentusername],strSubClass];
                NSError *error = nil;
                NSData *dataImg = [nsdata datawithcontentsofurl:[nsurl urlwithstring:strurl] options:NSDataReadingMappedIfSafe error:&error];
                if ([error code] == 0)
                {
                    //截取图片压缩
                    UIImage *imgCompress = [self image:[uiimage imagewithdata:dataimg] centerInSize:CGSizeMake(140, 140)];
                    NSData *dataCompress = UIImageJPEGRepresentation(imgCompress, 1.0);
                    
                    [self saveimage:datacompress nindex:indexpath.row picname:strsubclass];
                }
            }
        });
    }
    
    
    subVc.subCates = mutArrPics;
    [mutarrpics release];
    //    self.currentCate = cate;
    subVc.cateVC = self;
    
    self.tableView.scrollEnabled = NO;
    UIFolderTableView *folderTableView = (UIFolderTableView *)tableView;
    [foldertableview openfolderatindexpath:indexpath withcontentview:subvc.view
                                 openblock:^(uiview *subclassview, cftimeinterval duration, camediatimingfunction *timingfunction){
                                     // opening actions
                                 }
                                closeblock:^(uiview *subclassview, cftimeinterval duration, camediatimingfunction *timingfunction){
                                    // closing actions
                                }
                           completionblock:^{
                               // completed actions
                               self.tableview.scrollenabled = YES;
                           }];
    
}

```