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

pragma mark - 通過URL生成二維碼

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

pragma mark - 調整圖片大小

- (UIImage *)changeImageSizeWithCIImage:(CIImage *)ciImage andSize:(CGFloat)size{
    CGRect extent = CGRectIntegral(ciImage.extent);
    CGFloat scale = MIN(size/CGRectGetWidth(extent), size/CGRectGetHeight(extent));
    
    // 創建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]}];
    
    //從當前上下文獲取圖片
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    
    //結束圖像繪制上下文
    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{
    // 先獲得之前創建過的相冊
    PHFetchResult <PHAssetCollection *> *collectionResult = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
    for (PHAssetCollection *collection in collectionResult) {
        if ([collection.localizedTitle isEqualToString:photosName]) {
            return collection;
        }
    }
    
    // 如果相冊不存在,就創建新的相冊(文件夾)
    __block NSString *collectionId = nil; // __block修改block外部的變量的值
    // 這個方法會在相冊創建完畢后才會返回
    [[PHPhotoLibrary sharedPhotoLibrary] performChangesAndWait:^{
        // 新建一個PHAssertCollectionChangeRequest對象, 用來創建一個新的相冊
        collectionId = [PHAssetCollectionChangeRequest creationRequestForAssetCollectionWithTitle:photosName].placeholderForCreatedAssetCollection.localIdentifier;
    } error:nil];
    
    return [PHAssetCollection fetchAssetCollectionsWithLocalIdentifiers:@[collectionId] options:nil].firstObject;
}
/**
 *  返回相冊,避免重復創建相冊引起不必要的錯誤
 */
- (void)saveImage:(UIImage *) image{
    /*
     PHAsset : 一個PHAsset對象就代表一個資源文件,比如一張圖片
     PHAssetCollection : 一個PHAssetCollection對象就代表一個相冊
     */
    __block NSString *assetId = nil;
    // 1. 存儲圖片到"相機膠卷"
    [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{ // 這個block里保存一些"修改"性質的代碼
        // 新建一個PHAssetCreationRequest對象, 保存圖片到"相機膠卷"
        // 返回PHAsset(圖片)的字符串標識
        assetId = [PHAssetCreationRequest creationRequestForAssetFromImage:image].placeholderForCreatedAsset.localIdentifier;
    } completionHandler:^(BOOL success, NSError * _Nullable error) {
        if (error) {
            NSLog(@"保存圖片到相機膠卷中失敗");
            return;
        }
        
        NSLog(@"成功保存圖片到相機膠卷中");
        
        // 2. 獲得相冊對象
        PHAssetCollection *collection = [self collection];
        
        // 3. 將“相機膠卷”中的圖片添加到新的相冊
        [[PHPhotoLibrary sharedPhotoLibrary] performChanges:^{
            PHAssetCollectionChangeRequest *request = [PHAssetCollectionChangeRequest changeRequestForAssetCollection:collection];
            
            // 根據唯一標示獲得相片對象
            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];
            }];
        }];
    }];
}
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容