2009-10-26 10 views
6

Me he encontrado con esto unas cuantas veces y pensé que sería bueno publicarlo. ¿Cuál es tu mejor tamaño de imagen y/o lógica de recorte? La idea es que se llame a algún método con una imagen de destino, dimensiones y una bandera de recorte; esto devolvería o guardaría o la imagen que desee.Mejor tamaño y/o lógica de recorte

El mío está por debajo. Convertido de VB a C# así que sí, habrá pequeños errores pero la lógica es lo que estamos viendo.

// INIT 
// On/off 
bool WeAreCropping = true; 

// Get some dimensions 
int TargetWidth = RequestedWidth; 
int TargetHeight = RequestedHeight; 
int SourceWidth = SourceImage.Width; 
int SourceHeight = SourceImage.Height; 
int ResizeWidth = TargetWidth; 
int ResizeHeight = TargetHeight; 

// GET RESIZE VALUES 
// Are we cropping? 
if (WeAreCropping) { 

    // Get source and target aspect ratio 
    double SourceAspectRatio = SourceWidth/SourceHeight; 
    double TargetAspectRatio = TargetWidth/TargetHeight; 

    // Compare aspect ratios to find out if we should we resize by 
    // width or height or nothing 
    if (TargetAspectRatio < SourceAspectRatio) { 
     ResizeWidth = TargetHeight/SourceHeight * SourceWidth; 
    } 
    else if (TargetAspectRatio > SourceAspectRatio) { 
     ResizeHeight = TargetWidth/SourceWidth * SourceHeight; 
    } 
    else { 
     // Same aspect ratio 
    } 


} 
else { 

    // If the target image is bigger than the source 
    if (TargetWidth > SourceWidth && TargetHeight > SourceHeight) { 
     TargetWidth = SourceWidth; 
     TargetHeight = SourceHeight; 
    } 

    double Ratio = 0; 

    // What ratio should we resize it by 
    if (SourceWidth/TargetWidth > SourceHeight/TargetHeight) { 
     Ratio = SourceWidth/TargetWidth; 
    } 
    else { 
     Ratio = SourceHeight/TargetHeight; 
    } 

    ResizeWidth = Math.Ceiling(SourceWidth/Ratio); 

    ResizeHeight = Math.Ceiling(SourceHeight/Ratio); 
} 

// TIME TO DO SUMFINK 
// Resize the image using ResizeWidth and ResizeHeight 
// Do it 

if (WeAreCropping) { 
    // Crop the resized image at the center TargetWidth and TargetHeight 
    // Do it 
} 

Sospecho que esto podría ser mucho más elegante, así que tal vez podría hacerlo mejor.

Respuesta

4

Diría que debe utilizar tipos de geometría estándar como Rectangle y Size. Entonces, probablemente también debería admitir un caso de uso, cuando la persona que llama desea ajustar la imagen en un rectángulo más grande, pero aún desea mantener la proporción de tamaños de imagen original.

Una forma de implementar el cambio de tamaño puede encontrar here.

+0

Gracias por el enlace. – Maleks

+9

Hay un botón especial para "gracias" :)) –

+0

El enlace está roto – Flexicoder

0

Esto es probablemente un poco más complicado de lo que necesita, pero para un ejemplo de algunas técnicas de recorte avanzadas, check this out.

+0

El enlace me da un error de 500. –