簡體   English   中英

如何從本地URL獲取UIImage並將圖像發布到服務器?

[英]How to get UIImage from local url and post the image to server ?

如何從local url獲取UIImage並將圖像發布到服務器? 我的url如下:

file:///Users/macmini/Library/Developer/CoreSimulator/Devices/89104EAC-5BE1-4BEC-BE8E-7B8FFBF9CBD2/data/Media/DCIM/100APPLE/IMG_0005.JPG

以及如何減小此圖像的大小

< UIImage: 0x7b8d6170>, {3000, 2002}

先感謝您..

要從local url獲取圖片:

NSURL *localurl = [NSURL URLWithString:path];
NSData *data = [NSData dataWithContentsOfURL:localurl];
UIImage *img = [[UIImage alloc] initWithData:data];

將圖像發布到server

  - (void)sendImageToServer {
           UIImage *img= [UIImage imageNamed:@"image.png"];
           NSData *imageData = UIImagePNGRepresentation(img);
           NSString *postLength = [NSString stringWithFormat:@"%d", [imageData length]];

           // Init the URLRequest
           NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
           [request setHTTPMethod:@"POST"];
           [request setURL:[NSURL URLWithString:[NSString stringWithString:@"http://yoururl.domain"]]];
           [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
           [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
           [request setHTTPBody:imageData];

           NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
           if (connection) {
              // response data of the request
           }



 }

使用此代碼挑選圖像....

 if ([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypePhotoLibrary])
    {
        UIImagePickerController *imagePicker = [[UIImagePickerController alloc] init];
        imagePicker.sourceType =  UIImagePickerControllerSourceTypePhotoLibrary;
        imagePicker.delegate = self;
        imagePicker.allowsEditing = NO;
        [self presentViewController:imagePicker animated:YES completion:nil];
    }
    else
    {
        [self showMessage:@"This device doesn't support photo libraries."
                withTitle:@"Error"];
    }

使用以下代碼合並壓縮

#pragma clang diagnostic ignored "-Wdeprecated-declarations"

- (void) imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info {

    NSURL *refURL = [info valueForKey:UIImagePickerControllerReferenceURL];
    [picker.presentingViewController dismissViewControllerAnimated:YES completion:nil];

    // to    get the image image name use the following code
    ALAssetsLibraryAssetForURLResultBlock resultblock = ^(ALAsset *imageAsset)
    {
        ALAssetRepresentation *imageRep = [imageAsset defaultRepresentation];
        NSLog(@"[imageRep filename] : %@", [imageRep filename]);
        [_imageNameArray addObject:[imageRep filename]];
    };

    [_uploadTbleView reloadData];
    ALAssetsLibrary* assetslibrary = [[ALAssetsLibrary alloc] init];
    [assetslibrary assetForURL:refURL resultBlock:resultblock failureBlock:nil];


    UIImage* selectedImage = [info objectForKey:UIImagePickerControllerOriginalImage];
    NSData *imgData = UIImageJPEGRepresentation(selectedImage, 1.0);
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        //        [self.baseArray addObject:[self encodeToBase64String: selectedImage]];
        [self.baseArray addObject:[self base64forData:imgData]];
        //    NSLog(@"%@",[self encodeToBase64String: selectedImage]);
    });
    [self.imageSizeArray addObject: [NSNumber numberWithInteger:[imgData length]]];
    NSLog(@"Size of Image(bytes):%ld",[imgData length]);

}

以下是在上傳之前將圖像壓縮為base64的代碼

- (NSString*)base64forData:(NSData*) theData
{
    const uint8_t* input = (const uint8_t*)[theData bytes];
    NSInteger length = [theData length];

    static char table[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/=";

    NSMutableData* data = [NSMutableData dataWithLength:((length + 2) / 3) * 4];
    uint8_t* output = (uint8_t*)data.mutableBytes;

    NSInteger i;
    for (i=0; i < length; i += 3) {
        NSInteger value = 0;
        NSInteger j;
        for (j = i; j < (i + 3); j++) {
            value <<= 8;

            if (j < length) {
                value |= (0xFF & input[j]);
            }
        }

        NSInteger theIndex = (i / 3) * 4;
        output[theIndex + 0] =                    table[(value >> 18) & 0x3F];
        output[theIndex + 1] =                    table[(value >> 12) & 0x3F];
        output[theIndex + 2] = (i + 1) < length ? table[(value >> 6)  & 0x3F] : '=';
        output[theIndex + 3] = (i + 2) < length ? table[(value >> 0)  & 0x3F] : '=';
    }

    return [[NSString alloc] initWithData:data encoding:NSASCIIStringEncoding];
}

注意:

您的后端又必須解碼此base64數據以獲取圖像內容。 如果有任何問題,請再次回復我,我會幫助你

要從URL獲取圖像,您可以執行以下操作。

NSData *imageData = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
UIImage *image = [UIImage imageWithData:imageData];

要壓縮它,您必須再次將其轉換為NSData。

NSData *lowResImgData= UIImageJPEGRepresentation(highResImage,0.1 /*compressionQuality*/);
UIImage *lowResImage = [UIImage imageWithData:lowResImgData];

要減小圖像的大小,請使用以下方法

-(UIImage *)resizeImage:(UIImage *)image scaledToSize:(CGSize)targetSize
 {
   float actualHeight = image.size.height;
   float actualWidth = image.size.width;
   float maxHeight = targetSize.height;
   float maxWidth = targetSize.width;
   float imgRatio = actualWidth/actualHeight;
   float maxRatio = maxWidth/maxHeight;
   float compressionQuality = 0.50;//50 percent compression

    if (actualHeight > maxHeight || actualWidth > maxWidth)
     {
       if(imgRatio < maxRatio)
         {
           //adjust width according to maxHeight
           imgRatio = maxHeight / actualHeight;
            actualWidth = imgRatio * actualWidth;
            actualHeight = maxHeight;
         }
    else if(imgRatio > maxRatio)
{
    //adjust height according to maxWidth
    imgRatio = maxWidth / actualWidth;
    actualHeight = imgRatio * actualHeight;
    actualWidth = maxWidth;
}
else
{
    actualHeight = maxHeight;
    actualWidth = maxWidth;
}
 }

CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
UIGraphicsBeginImageContext(rect.size);
[image drawInRect:rect];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality);
UIGraphicsEndImageContext();
return [UIImage imageWithData:imageData];

}

請查看以下網址以在您的服務器中uppload圖像。

ios使用HTTP POST上傳圖像和文本

要壓縮UIImage,它取決於你的需求。根據壓縮的質量或根據大小的壓縮。

第一種方式(質量),使用API​​如下:

UIImageJPEGRepresentation(UIImage * __nonnull image, CGFloat compressionQuality)

第二種方式,使用代碼如下:

+ (UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize
    {
    // Create a graphics image context
    UIGraphicsBeginImageContext(newSize);

    // Tell the old image to draw in this new context, with the desired
    // new size
    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];

    // Get the new image from the context
    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();

    // End the context
    UIGraphicsEndImageContext();

    // Return the new image.
    return newImage;
}

要將本地圖像文件上傳到服務器,如果您使用AFNetWorking 3.x,此類代碼可能適用於您:

AFHTTPSessionManager *manager = [[AFHTTPSessionManager alloc] initWithBaseURL:[NSURL URLWithString:host]];
[manager POST:path parameters:params constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
    //local file url,for you is  /Users/macmini/Library/Developer/CoreSimulator/Devices/89104EAC-5BE1-4BEC-BE8E-7B8FFBF9CBD2/data/Media/DCIM/100APPLE/IMG_0005.JPG
    NSURL *url = [NSURL fileURLWithPath:fileUrl];
    [formData appendPartWithFileURL:url name:name fileName:fileName mimeType:mimeType error:nil];
} progress:^(NSProgress * _Nonnull uploadProgress) {

} success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    if (successBlock) {
        if (responseObject) {
            successBlock(responseObject);
        }
    }
} failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
    if (failureBlock) {
        HttpFailResponse *failResponse = [self _kep_configureFailResponseWithError:error];
        failureBlock(failResponse);
    }
}];

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM