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)

 

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)

 

4. 通过上面的结果,可以看出,同样的压缩比,压缩出来的照片大小是一样的;

   但是我在比较上面相同大小文件的MD5时发现是不一样的;

   所以理论上MAC和iOS上的JPEG压缩是一致的,但并不是完全一致!

测试程序下载!

 

posted @ 2017-04-24 09:59  cocoajin  阅读(2755)  评论(0编辑  收藏  举报