Comprimir imágenes para reducir el tamaño del archivo
Estoy creando una aplicación que le permite al usuario tomar una foto o seleccionar una de la biblioteca en el iPhone y subirla al servidor de Parse.
El problema que estoy enfrentando es con respecto al tamaño del archivo.
He leído sobre lo que hacen los grandes jugadores como Facebook, Twitter, Instagram y Google con respecto a la resolución y el tamaño del archivo, pero no puedo acercarme a eso.
Estoy seguro de que tienen el mejor código y las mejores herramientas para hacerlo, pero estaré encantado de implementarlo lo mejor posible con los procesos regulares de iOS.
Esto es lo que estoy haciendo ahora mismo:
- (UIImage *)normalResImageForAsset:(ALAsset*)asset
{
// Convert ALAsset to UIImage
UIImage *image = [self highResImageForAsset:asset];
// Determine output size
CGFloat maxSize = 1024.0f;
CGFloat width = image.size.width;
CGFloat height = image.size.height;
CGFloat newWidth = width;
CGFloat newHeight = height;
// If any side exceeds the maximun size, reduce the greater side to 1200px and proportionately the other one
if (width > maxSize || height > maxSize) {
if (width > height) {
newWidth = maxSize;
newHeight = (height*maxSize)/width;
} else {
newHeight = maxSize;
newWidth = (width*maxSize)/height;
}
}
// Resize the image
CGSize newSize = CGSizeMake(newWidth, newHeight);
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
// Set maximun compression in order to decrease file size and enable faster uploads & downloads
NSData *imageData = UIImageJPEGRepresentation(newImage, 0.0f);
UIImage *processedImage = [UIImage imageWithData:imageData];
return processedImage;
}
Estoy tratando de hacer que 1024px sea el tamaño máximo permitido (ambos con altura o altura) para comenzar algunas restricciones allí y luego estoy aplicando la compresión máxima para reducir el tamaño.
Esto funciona y reduce aproximadamente el 50% del tamaño de la imagen sin JPEG realmente dañinos, pero aún es mucho. Especialmente si las fotos se toman con la cámara del teléfono y se cargan. La imagen procesada todavía puede tener fácilmente un tamaño de 1 MB, lo que es demasiado.
Supongo que podría faltar algún paso útil o usar la técnica incorrecta.
Cualquier comentario sería muy apreciado.