天天看點

ios mac 對照片進行JPEG壓縮

ios mac 對照片進行JPEG壓縮

1. 在iOS上可以使用 API UIImageJPEGRepresentation 對照片資料進行JPEG壓縮;

   我們知道iOS其實是MAC OS 的移植,那麼MAC上肯定也有相應的JPEG壓縮方法;

   在mac上了,找了NSImage的API沒有發現直接的JPEG壓縮方法;

   但是有NSBitmapImageRep,下面來測試一下,iOS和MAC上的JPEG壓縮是否一緻;

2. 首先用iOS 來壓縮一張照片

UIImage *timg = [UIImage imageWithContentsOfFile:@"/Users/cc/Desktop/testiOS/IMG_0420.PNG"];
    for (int i = 0; i <10; i++) {
        NSData *cd = UIImageJPEGRepresentation(timg, (i+1)/10.0f);
        [cd writeToFile:[NSString stringWithFormat:@"/Users/cc/Desktop/testiOS/com%.1f.jpeg",(i+1)/10.0f] atomically:YES];
    }      

得到結果:(壓縮比0.1~1.0)

ios mac 對照片進行JPEG壓縮

3. MAC API對照片進行JPEG壓縮

//參數校驗
        if (argc!=4) {
            printf("參數錯誤,請檢測!\n");
            printf("本程式主要是對圖檔進行JPEG壓縮\n");
            printf("示例:./JPEGCompress /xxpath/imgfile /xxpath/out.jpeg 0.4 \n");
            printf("參數一:要壓縮的圖檔;參數二:輸出路徑;參數三:壓縮比0.1~1.0之間\n");
            
            return -1000;
        }
    
        NSString *inPath = [NSString stringWithCString:argv[1] encoding:NSUTF8StringEncoding];
        NSString *outPath = [NSString stringWithCString:argv[2] encoding:NSUTF8StringEncoding];
        float compress =  [[NSString stringWithCString:argv[3] encoding:NSUTF8StringEncoding] floatValue];
        
        NSImage *simg = [[NSImage alloc]initWithContentsOfFile:inPath];
        NSData *imgDt = [simg TIFFRepresentation];
        NSBitmapImageRep *imageRep = [NSBitmapImageRep imageRepWithData:imgDt];
        NSDictionary *imageProps = [NSDictionary dictionaryWithObject:[NSNumber numberWithFloat:compress] forKey:NSImageCompressionFactor];
        imgDt = [imageRep representationUsingType:NSJPEGFileType properties:imageProps];
        
        int ret = [imgDt writeToFile:outPath atomically:YES];
        if (ret>0) {
            printf("in: %s\nout: %s\ncompress: %s\nSUCCESS\n",argv[1],argv[2],argv[3]);
        }else
        {
            printf("FAILURE!\n");
        }
        return ret;      

得到結果:壓縮比(0.1~1.0)

ios mac 對照片進行JPEG壓縮

4. 通過上面的結果,可以看出,同樣的壓縮比,壓縮出來的照片大小是一樣的;

   但是我在比較上面相同大小檔案的MD5時發現是不一樣的;

   是以理論上MAC和iOS上的JPEG壓縮是一緻的,但并不是完全一緻!

測試程式下載下傳!