2011-07-13 37 views
0

我正在保存到相冊,我希望該文件是.png,但它保存爲.jpeg文件?甚至可以將.png保存到相冊中?需要另存爲.png,但是我得到.jpg

這裏是我的代碼:

CGContextRef MyCreateBitmapContext (int pixelsWide,int pixelsHigh) 
{ 
    CGContextRef context = NULL; 
    //CGColorSpaceRef colorSpace; 
    void * bitmapData; 
    int bitmapByteCount; 
    int bitmapBytesPerRow; 
    bitmapBytesPerRow = (pixelsWide * 4); 
    bitmapByteCount = (bitmapBytesPerRow * pixelsHigh); 
    //colorSpace = CGColorSpaceCreateWithName(kCGColorSpaceGenericRGB); 
    CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); 
    bitmapData = malloc(bitmapByteCount); 

    if (bitmapData == NULL) 
    { 
     fprintf (stderr, "Memory not allocated!"); 
     return NULL; 
    } 
    context = CGBitmapContextCreate (bitmapData, 
            pixelsWide, 
            pixelsHigh, 
            8,//bits per component 
            bitmapBytesPerRow, 
            colorSpace, 
            kCGImageAlphaPremultipliedLast); 

    if (context== NULL) 
    { 
     free (bitmapData); 
     fprintf (stderr, "Context not created!"); 
     return NULL; 
    } 
    CGColorSpaceRelease(colorSpace); 
    return context; 
} 

和:

- (IBAction)save:(id)sender{ 

    myBitmapContext = MyCreateBitmapContext (400, 300); 

    // ********** Your drawing code here ********** 

    CGContextSetRGBFillColor (myBitmapContext, 1, 0, 0, 1); 
    CGContextFillRect (myBitmapContext, CGRectMake (0, 0, 400, 300)); 


    // ********** Your drawing code here ********** 


    CGImageRef imageRef = CGBitmapContextCreateImage(myBitmapContext); 
    UIImage * image = [[UIImage alloc] initWithCGImage:imageRef]; 

    //NSData* imdata = UIImagePNGRepresentation (image);// get PNG representation 

    //UIImage* im2 = [UIImage imageWithData:imdata]; // wrap UIImage around PNG representation 

    UIImageWriteToSavedPhotosAlbum(image, nil, nil, nil); // save to photo album 

    [image release]; 

    CGImageRelease(imageRef); 
    CGContextRelease(myBitmapContext); 
} 

任何想法

+0

'UIImageWriteToSavedPhotosAlbum'獲取圖像數據並將jpg寫入相冊。我相信它並不關心底層圖像文件是什麼。作爲黑暗中的刺,請嘗試使用「UISaveVideoAtPathToSavedPhotosAlbum」。 – amattn

+0

謝謝amattn,我會在稍後看看。 – mtompson

回答

3

UIImage千恩萬謝沒有關聯的文件類型。你的代碼需要UIImage,提取PNG數據,並構造一個新的UIImage只是浪費CPU週期。生成的圖像應該與原始圖像相同。 UIImageWriteToSavedPhotosAlbum()會保存JPEG,因爲它假設照片被保存到相冊中的照片就是照片。 JPEG是照片的首選格式。

您可能想要提交一個bug report,請求將PNG保存到照片相冊的機制。

+0

感謝那個凱文,我已經編輯了代碼來刪除.png元素。 (尚未測試)我可以忍受.jpegs,但我會喜歡.png。我甚至需要這行:UIImage * image = [[UIImage alloc] initWithCGImage:imageRef];或者我可以直接在UIImageWriteToSavedPhotosAlbum方法中使用imageRef? – mtompson

+1

不,你仍然需要創建一個UIImage *。 CGImageRef和UIImage不是免費橋接的。但是,UIImage *實際上只是CGImageRef的一個包裝,所以當你這樣做的時候你並沒有複製圖像數據。 –