2011-06-03 27 views
5

Utilizo Jquery Jcrop para recortar mis imágenes. Ahora estoy implementando un control deslizante para cambiar el tamaño de la imagen. Quiero que el recorte y cambio de tamaño ocurra en la misma página.Cambiar el tamaño de la imagen que utiliza Jcrop

lo hago de esta manera:

$(document).ready(function() { 


    var img = $('#cropbox')[0]; // Get my img elem 
    var orgwidth, orgheight; 
    $("<img/>") // Make in memory copy of image to avoid css issues 
     .attr("src", $(img).attr("src")) 
     .load(function() { 
      orgwidth = this.width; // Note: $(this).width() will not 
      orgheight = this.height; // work for in memory images. 
     }); 

    $('#cropbox').Jcrop({ 
     onSelect: updateCoords 
    }); 

    $("#imageslider").slider({ 
     value: 100, 
     max: 100, 
     min: 1, 
     slide: function(event, ui) { 
      //$('ul#grid li').css('font-size',ui.value+"px"); 
      resizeImage(orgwidth, orgheight); 
     } 
    }); 

}); 

Y mi función simple resizeImage:

function resizeImage(orgwidth, orgheight) { 
    var value = $('#imageslider').slider('option', 'value'); 
    var width = orgwidth * (value/100); 
    var height = orgheight * (value/100); 
    $('#cropbox').width(width); 
    $('#cropbox').height(height); 
    $('#tester').val("org: "+orgwidth+" now: "+width); 
} 

El problema es que, tan pronto se enciende el Jcrop no puedo cambiar el tamaño de la imagen. ¿Cómo puedo usar ambas funciones al mismo tiempo?

Respuesta

5

Terminé destruyendo el jCrop mientras redimensionaba y volvía a colocarlo después de cambiar el tamaño. Gracias de cualquier manera. Código:

 function resizeImage(orgwidth, orgheight) { 
     jcrop_api.destroy(); 

     var value = $('#imageslider').slider('option', 'value'); 
     var width = orgwidth * (value/100); 
     var height = orgheight * (value/100); 
     $('#cropbox').width(width); 
     $('#cropbox').height(height); 
     $('#rw').val(width); 
     $('#rh').val(height); 

     initJcrop(); 

    } 
0

Si lo que desea es que el cambio de tamaño debe ser proporcional, no creo que necesita el control deslizante (ya que parece ser incompatible con jCrop). Puede usar jCrop y en el evento onChange, garantizar la proporcionalidad (es decir, implementar la función resizeImage, modificada).
Eso es lo que creo.

3

Tuve la misma tarea que hacer: cambiar el tamaño de la imagen con un control deslizante donde se aplica jCrop. Hay algunos elementos más que tienes que cambiar el tamaño también que jCrop creó, no solo la imagen. Terminé parcheando el plugin jCrop y aquí está el parche para la última jCrop-0.9.10.

Parche su jCrop. Si usted no sabe cómo aplicar el parche, sólo hay que poner la función resizeImage a la línea 1578 de jCrop (versión unimified por supuesto):

--- /home/dr0bz/Desktop/jquery.Jcrop.js 
+++ /home/dr0bz/workspace/profile_tuning/js/lib/jquery.Jcrop.js 
@@ -1573,6 +1573,15 @@ 
     ui: { 
     holder: $div, 
     selection: $sel 
+  }, 
+  
+  resizeImage: function(width, height) { 
+  boundx = width; 
+  boundy = height; 
+  $([$img2, $img, $div, $trk]).each(function(index, element) 
+  { 
+   element.width(width).height(height); 
+  }); 
     } 
    }; 

Obtener el API jCrop:

var jCropApi; 
$('#photo').Jcrop({}, function() 
{ 
    jCropApi = this; 
}); 

Calc nueva altura y ancho Si tu lo están haciendo con un control deslizante, dejar que el control deslizante decir devolver el nuevo ancho de la imagen y calcular la nueva altura con relación de aspecto de la imagen:

var aspectRatio = width/height; 
// newWidth returned by slider 
var newHeight = Math.round(width/aspectRatio); 
jCropApi.resizeImage(newWidth, newHeight); 

Hay algunos otros puntos a tener un ojo en. Después de cada cambio de tamaño, debe ver que el área de recorte todavía está en la ventana gráfica de la imagen. Si lo necesita, podría publicar la fuente completa de cómo lo he hecho por mí: jCrop + jQuery ui slider para cambiar el tamaño de la imagen.

Saludos

+1

Usando esto como una base He presentado una solicitud de extracción aquí: https://github.com/tapmodo/Jcrop/pull/69 – homerjam

+0

¡Gracias! Funcionando bien – user706420

1

Lo que también se puede hacer es hacer uso de la función setImage de Jcrop, cuando cambia el control deslizante, llame al setImage con la API Jcrop y establecer nuevos valores de anchura y altura de esta manera:

var jcrop_api; 

$('#cropbox').Jcrop({ 
    onSelect: updateCoords 
}, function() { 
    jcrop_api = this; 
}); 

$("#imageslider").slider({ 
    value: 100, 
    max: 100, 
    min: 1, 
    slide: function(event, ui) { 
     var value = $('#imageslider').slider('option', 'value'); 
     var width = orgwidth * (value/100); 
     var height = orgheight * (value/100); 
     jcrop_api.setImage($(img).attr("src"), function() { 
      this.setOptions({ 
       boxWidth: width, 
       boxHeight: height 
      }); 
     }); 
     $('#tester').val("org: "+orgwidth+" now: "+width); 
    } 
}); 

Lo que no estoy seguro acerca de esta técnica es si es la mejor solución porque cada vez que llamas a la función setImage, jcrop crea un nuevo objeto Image.

0

Como una extensión de la respuesta de Hermann Bier, he agregado la animación jquery. El cambio de tamaño se ve mucho mejor cuando es animado :)

Implementado en Jcrop Versión: jquery.Jcrop.js v0.9.12

localizar el código:

ui: { 
    holder: $div, 
    selection: $sel 
    } 

en torno jquery.Jcrop.js línea 1573 y sustituirla por:

ui: { 
    holder: $div, 
    selection: $sel 
    }, 
    resizeImage: function(width, height) { 
    animationsTid = 500; 
    boundx = width; 
    boundy = height; 

    $($img2).animate({ 
     width: width, 
     height: height, 
    }, { duration: animationsTid, queue: false }); 

    $($img).animate({ 
     width: width, 
     height: height, 
    }, { duration: animationsTid, queue: false }); 

    $($div).animate({ 
     width: width, 
     height: height, 
    }, { duration: animationsTid, queue: false }); 

    $($trk).animate({ 
     width: width, 
     height: height, 
    }, { duration: animationsTid, queue: false }); 

    /* 
    //Old way of resizing, but without animation 
    $([$img2, $img, $div, $trk]).each(function(index, element){ 
     element.width(width).height(height); 
    }); 
    */ 
    } 

llamada a la función va a animar el cambio de tamaño. dude en eliminar el código entre/* */- Me lo quedé como una referencia

feliz :) Codificación

Cuestiones relacionadas