2012-04-26 97 views
3

我正在嘗試使用iPhone 4及更高版本在Objective-C中縮放圖像,以便儘快將其發送到服務器。目前全尺寸的圖像已經過時了。調整圖像大小Objective-C

減員我想目前是:

CGSize imageSize; 

imageSize = CGSizeMake(484, 888); 

UIImage *img = [UIImage imageWithContentsOfFile:path]; 

UIGraphicsBeginImageContext(imageSize); 
[img drawInRect:CGRectMake(0,0,imageSize.width,imageSize.height)]; 
UIImage* realfrontImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
NSData *frontImageData = UIImageJPEGRepresentation(realfrontImage, 1.0); 

這給我的320x460我怎麼得到它,我想484x888大小的圖像。

任何幫助將不勝感激。

+0

xcode只是一個編輯器。 – vikingosegundo 2012-04-26 13:40:12

+0

感謝編輯很累。感謝迄今爲止提出的想法。它們與我目前使用的非常相似,當我在服務器上查看它時,我最終得到尺寸爲320x426的圖像 – chrisw 2012-04-26 13:58:53

+0

您確定連接沒有問題嗎?我的意思是,如果上傳到您的服務器受到干擾,它會給您留下未完成的圖像上傳,但是,這將主要影響圖像的高度。 – 2012-04-29 17:57:40

回答

0

//調用這個函數與調整大小比...

-(UIImage*)scaleByRatio:(float) scaleRatio 
{ 
    CGSize scaledSize = CGSizeMake(self.size.width * scaleRatio, self.size.height * scaleRatio); 
    CGColorSpaceRef colorSpace; 
    int bitmapBytesPerRow; 
    bitmapBytesPerRow = (size.width * 4); 

    //The output context. 
    UIGraphicsBeginImageContext(scaledSize); 
    CGContextRef context = context = CGBitmapContextCreate (NULL, 
          scaledSize .width, 
          scaledSize .height, 
          8,  // bits per component 
          bitmapBytesPerRow, 
          colorSpace, 
          kCGImageAlphaPremultipliedLast); 

//Percent (101%)  
#define SCALE_OVER_A_BIT 1.01 

//Scale. 
CGContextScaleCTM(context, scaleRatio * SCALE_OVER_A_BIT, scaleRatio *  SCALE_OVER_A_BIT); 
[self drawAtPoint:CGPointZero]; 

    //End? 
    UIImage *scaledImage = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
return scaledImage; 
} 

希望,這將幫助你......

+0

對不起,但我該如何使用此功能我得到一個C99警告是無效 – chrisw 2012-04-26 15:07:37

+0

'#import '... – Nit 2012-04-26 17:56:55

+0

我必須使用它作爲UIImage類別嗎? – 2012-10-02 13:39:24

4
-(UIImage*)imageWithImage:(UIImage*)image scaledToSize:(CGSize)newSize { 
    UIGraphicsBeginImageContext(newSize); 
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)]; 
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();  
    UIGraphicsEndImageContext(); 
    return newImage; 
} 

使用此方法縮小您的圖像。

+0

如果我發送從這個方法檢索到的圖像,當我將它發送到服務器時,我得到一個320x426的圖像,它似乎只是像屏幕截圖一樣大小的屏幕。 – chrisw 2012-04-26 14:17:25

+0

我在CGBitmapContextCreate上得到EXC_BAD_ACCESS – chrisw 2012-04-26 15:22:13

+0

我發現這種方式有內存泄漏,之後iOS 5.0看到以下內容! http://stackoverflow.com/a/4712537/1752988 – 2014-04-15 20:11:38