生成二維碼(改變圖像大小) UImage切圓角 保存圖片并創(chuàng)建圖冊到相冊

pragma mark - 通過URL生成二維碼

- (UIImage *) create2DCodeImageWithSize:(CGFloat) size codeUrl:(NSString *) codeUrl{
    
    // 實(shí)例化二維碼濾鏡
    CIFilter *filter = [CIFilter filterWithName:@"CIQRCodeGenerator"];
    
    // 恢復(fù)濾鏡的默認(rèn)屬性 (因為濾鏡有可能保存上一次的屬性)
    [filter setDefaults];
    
    // 將字符串轉(zhuǎn)換成NSdata
    NSData *data  = [codeUrl dataUsingEncoding:NSUTF8StringEncoding];
    
    // 通過KVO設(shè)置濾鏡, 傳入data, 將來濾鏡就知道要通過傳入的數(shù)據(jù)生成二維碼
    [filter setValue:data forKey:@"inputMessage"];
    
    // 生成二維碼
    CIImage *outputImage = [filter outputImage];
    
    UIImage *image = [self changeImageSizeWithCIImage:outputImage andSize:size];
    return image;
}

pragma mark - 調(diào)整圖片大小

- (UIImage *)changeImageSizeWithCIImage:(CIImage *)ciImage andSize:(CGFloat)size{
    CGRect extent = CGRectIntegral(ciImage.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 創(chuàng)建bitmap;
    size_t width = CGRectGetWidth(extent) * scale;
    size_t height = CGRectGetHeight(extent) * scale;
    CGColorSpaceRef cs = CGColorSpaceCreateDeviceGray();
    CGContextRef bitmapRef = CGBitmapContextCreate(nil, width, height, 8, 0, cs, (CGBitmapInfo)kCGImageAlphaNone);
    CIContext *context = [CIContext contextWithOptions:nil];
    CGImageRef bitmapImage = [context createCGImage:ciImage fromRect:extent];
    CGContextSetInterpolationQuality(bitmapRef, kCGInterpolationNone);
    CGContextScaleCTM(bitmapRef, scale, scale);
    CGContextDrawImage(bitmapRef, extent, bitmapImage);
    // 保存bitmap到圖片
    CGImageRef scaledImage = CGBitmapContextCreateImage(bitmapRef);
    CGContextRelease(bitmapRef);
    CGImageRelease(bitmapImage);
    return [UIImage imageWithCGImage:scaledImage];
}

pragma mark - 繪制并保存圖片

- (void) clickDownloadButton {
    
    UIGraphicsBeginImageContext(CGSizeMake(640, 910));
    
    UIImage *backImage = [UIImage imageNamed:@"download_pic"];
    [backImage drawInRect:CGRectMake(0, 0, 640, 910)];
    
    UIImage *imageface = [self create2DCodeImageWithSize:370 codeUrl:_codeUrl];
    [imageface drawInRect:CGRectMake(135, 270, 370, 370)];
    
    UIImage *iconImage = [self makeRoundedImage:_userIconImageView.image radius:50];
    [iconImage drawInRect:CGRectMake(70, 126, 100, 100)];

    NSString *str1 = _userNameLabel.text;
    [str1 drawAtPoint:CGPointMake(200, 136) withAttributes:@{NSForegroundColorAttributeName:RGBCOLOR(37, 182, 237),NSFontAttributeName:[UIFont systemFontOfSize:32]}];
    
    NSString *str2 = _userShopLabel.text;
    [str2 drawAtPoint:CGPointMake(200, 186) withAttributes:@{NSForegroundColorAttributeName:RGBCOLOR(69, 69, 69),NSFontAttributeName:[UIFont systemFontOfSize:28]}];
    
    //從當(dāng)前上下文獲取圖片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    //結(jié)束圖像繪制上下文
    UIGraphicsEndImageContext();
    
    //保存到相冊
//    UIImageWriteToSavedPhotosAlbum(image, self, @selector(bigPicImage:didFinishSavingWithError:contextInfo:), nil);
    
    [self saveImage:image];
}

pragma mark - UIImage切圓角

-(UIImage *) makeRoundedImage:(UIImage *) image
                     radius: (float) radius;
{
  // 截取一部分圖片
  CGRect rect = CGRectMake( 0, 0, MIN(image.size.width, image.size.height), MIN(image.size.width, image.size.height));
  CGImageRef imageRef = CGImageCreateWithImageInRect(image.CGImage, rect);
  UIImage *bg = [UIImage imageWithCGImage:imageRef];
  CGImageRelease(imageRef);
  
  CALayer *imageLayer = [CALayer layer];
  imageLayer.frame = CGRectMake(0, 0, 2 * radius, 2 * radius);
  imageLayer.contentsScale = [[UIScreen mainScreen] scale];
  imageLayer.contents = (id) bg.CGImage;
  imageLayer.cornerRadius = radius;
  imageLayer.masksToBounds = YES;
  
  UIGraphicsBeginImageContext(CGSizeMake(2 * radius, 2 * radius));
  [imageLayer renderInContext:UIGraphicsGetCurrentContext()];
  UIImage *roundedImage = UIGraphicsGetImageFromCurrentImageContext();
  UIGraphicsEndImageContext();
  return roundedImage;

}
- (PHAssetCollection *)collection{
    // 先獲得之前創(chuàng)建過的相冊
    PHFetchResult <PHAssetCollection *> *collectionResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection *collection in collectionResult) {
        if ([collection.localizedTitle isEqualToString:photosName]) {
            return collection;
        }
    }
    
    // 如果相冊不存在,就創(chuàng)建新的相冊(文件夾)
    __block NSString *collectionId = nil; // __block修改block外部的變量的值
    // 這個方法會在相冊創(chuàng)建完畢后才會返回
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        // 新建一個PHAssertCollectionChangeRequest對象, 用來創(chuàng)建一個新的相冊
        collectionId = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:photosName].placeholderForCreatedAssetCollection.localIdentifier;
    } error:nil];
    
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[collectionId] options:nil].firstObject;
}
/**
 *  返回相冊,避免重復(fù)創(chuàng)建相冊引起不必要的錯誤
 */
- (void)saveImage:(UIImage *) image{
    /*
     PHAsset : 一個PHAsset對象就代表一個資源文件,比如一張圖片
     PHAssetCollection : 一個PHAssetCollection對象就代表一個相冊
     */
    __block NSString *assetId = nil;
    // 1. 存儲圖片到"相機(jī)膠卷"
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ // 這個block里保存一些"修改"性質(zhì)的代碼
        // 新建一個PHAssetCreationRequest對象, 保存圖片到"相機(jī)膠卷"
        // 返回PHAsset(圖片)的字符串標(biāo)識
        assetId = [PHAssetCreationRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset.localIdentifier;
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (error) {
            NSLog(@"保存圖片到相機(jī)膠卷中失敗");
            return;
        }
        
        NSLog(@"成功保存圖片到相機(jī)膠卷中");
        
        // 2. 獲得相冊對象
        PHAssetCollection *collection = [self collection];
        
        // 3. 將“相機(jī)膠卷”中的圖片添加到新的相冊
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];
            
            // 根據(jù)唯一標(biāo)示獲得相片對象
            PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetId] options:nil].firstObject;
            // 添加圖片到相冊中
            [request addAssets:@[asset]];
        } completionHandler:^(BOOL success, NSError * _Nullable error) {
            if (error) {
                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                    
                    [MBProgressHUD ZP_ShowRemindUserText:@"保存到相冊失敗" toView:self.superview inPeriod:1 yOffset:200];
                }];
                return;
            }
            
//            PHAsset *asset = [PHAsset fetchAssetsWithLocalIdentifiers:@[assetId] options:nil].firstObject;
//            [PHAssetCreationRequest deleteAssets:@[asset]];
            [[NSOperationQueue mainQueue] addOperationWithBlock:^{

                [MBProgressHUD ZP_ShowRemindUserText:@"圖片已保存到相冊/掌上好房通" toView:self.superview inPeriod:1 yOffset:200];
            }];
        }];
    }];
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末缔刹,一起剝皮案震驚了整個濱河市趣苏,隨后出現(xiàn)的幾起案子裕便,更是在濱河造成了極大的恐慌儒拂,老刑警劉巖蛋辈,帶你破解...
    沈念sama閱讀 221,888評論 6 515
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件瑟慈,死亡現(xiàn)場離奇詭異,居然都是意外死亡仔雷,警方通過查閱死者的電腦和手機(jī)乾胶,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 94,677評論 3 399
  • 文/潘曉璐 我一進(jìn)店門抖剿,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人识窿,你說我怎么就攤上這事∧匀冢” “怎么了喻频?”我有些...
    開封第一講書人閱讀 168,386評論 0 360
  • 文/不壞的土叔 我叫張陵,是天一觀的道長肘迎。 經(jīng)常有香客問我甥温,道長,這世上最難降的妖魔是什么妓布? 我笑而不...
    開封第一講書人閱讀 59,726評論 1 297
  • 正文 為了忘掉前任姻蚓,我火速辦了婚禮,結(jié)果婚禮上匣沼,老公的妹妹穿的比我還像新娘狰挡。我一直安慰自己,他們只是感情好释涛,可當(dāng)我...
    茶點(diǎn)故事閱讀 68,729評論 6 397
  • 文/花漫 我一把揭開白布加叁。 她就那樣靜靜地躺著,像睡著了一般唇撬。 火紅的嫁衣襯著肌膚如雪它匕。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 52,337評論 1 310
  • 那天窖认,我揣著相機(jī)與錄音豫柬,去河邊找鬼。 笑死扑浸,一個胖子當(dāng)著我的面吹牛烧给,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播首装,決...
    沈念sama閱讀 40,902評論 3 421
  • 文/蒼蘭香墨 我猛地睜開眼创夜,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了仙逻?” 一聲冷哼從身側(cè)響起驰吓,我...
    開封第一講書人閱讀 39,807評論 0 276
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎系奉,沒想到半個月后檬贰,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 46,349評論 1 318
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡缺亮,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,439評論 3 340
  • 正文 我和宋清朗相戀三年翁涤,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片。...
    茶點(diǎn)故事閱讀 40,567評論 1 352
  • 序言:一個原本活蹦亂跳的男人離奇死亡葵礼,死狀恐怖号阿,靈堂內(nèi)的尸體忽然破棺而出,到底是詐尸還是另有隱情鸳粉,我是刑警寧澤扔涧,帶...
    沈念sama閱讀 36,242評論 5 350
  • 正文 年R本政府宣布,位于F島的核電站届谈,受9級特大地震影響枯夜,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜艰山,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,933評論 3 334
  • 文/蒙蒙 一湖雹、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧曙搬,春花似錦摔吏、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,420評論 0 24
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至搂擦,卻和暖如春稳诚,著一層夾襖步出監(jiān)牢的瞬間,已是汗流浹背瀑踢。 一陣腳步聲響...
    開封第一講書人閱讀 33,531評論 1 272
  • 我被黑心中介騙來泰國打工扳还, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留,地道東北人橱夭。 一個月前我還...
    沈念sama閱讀 48,995評論 3 377
  • 正文 我出身青樓氨距,卻偏偏與公主長得像,于是被迫代替她去往敵國和親棘劣。 傳聞我的和親對象是個殘疾皇子俏让,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,585評論 2 359

推薦閱讀更多精彩內(nèi)容