Jcrop неправильно обрезает изображения

Мой jcrop-код

$(function(){

// Create variables (in this scope) to hold the API and image size
var jcrop_api,
    boundx,
    boundy,

    // Grab some information about the preview pane
    $preview = $('#preview-pane'),
    $pcnt = $('#preview-pane .preview-container'),
    $pimg = $('#preview-pane .preview-container img'),

    xsize = $pcnt.width(),
    ysize = $pcnt.height();

//console.log('init',[xsize,ysize]);
$('#target').Jcrop({
  onChange: updateInfo,
  onSelect: updateInfo,
  onRelease: clearInfo,
  setSelect: [0, 0, 150, 180],
  boxWidth: 400, boxHeight: 300,
  allowMove: true, 
  allowResize: true, 
  allowSelect: true,
  aspectRatio: xsize / ysize
},function(){
  // Use the API to get the real image size
  var bounds = this.getBounds();
  boundx = bounds[0];
  boundy = bounds[1];
  // Store the API in the jcrop_api variable
  jcrop_api = this;

  // Move the preview into the jcrop container for css positioning
  $preview.appendTo(jcrop_api.ui.holder);
});


   // update info by cropping (onChange and onSelect events handler)
function updateInfo(e) {
    if (parseInt(e.w) > 0) {
        var rx = xsize / e.w;
        var ry = ysize / e.h;

        $pimg.css({
            width : Math.round(rx * boundx) + 'px',
            height : Math.round(ry * boundy) + 'px',
            marginLeft : '-' + Math.round(rx * e.x) + 'px',
            marginTop : '-' + Math.round(ry * e.y) + 'px'
        });
    }
    $('#x1').val(e.x);
    $('#y1').val(e.y);
    $('#w').val(e.w);
    $('#h').val(e.h);
};

// clear info by cropping (onRelease event handler)
function clearInfo() {
    $('#w').val('');
    $('#h').val('');
};


   });

   Java controller which handles it

@RequestMapping(value = "/editProfileImage", method = RequestMethod.POST)
public @ResponseBody
FileMeta edit(MultipartHttpServletRequest request,
        @RequestParam(value = "x1") final int x1,
        @RequestParam(value = "y1") final int y1,
        @RequestParam(value = "w") final int w,
        @RequestParam(value = "h") final int h) throws Exception {
    Iterator<String> itr = fileIterator(request);
    MultipartFile mpf = null;
    final FileMeta fileMeta = new FileMeta();
    // 2. get each file
    while (itr.hasNext()) {
        mpf = getMultipartFile(request, itr);
        checkIfEmpty(mpf);
        checkifValidFormat(mpf);

        final BufferedImage subImage = getBufImage(mpf).getSubimage(x1, y1, w, h);

        //final BufferedImage resizedImage = resizeImage(subImage);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        ImageIO.write(subImage,
                mpf.getContentType().replace("image/", ""), baos);
        final Account account = accountManager.findBySigin((String) request
                .getAttribute("account"));
        profilePictureService.saveProfilePicture(account.getId(),
                baos.toByteArray());

        prepareMetaInformation(mpf, fileMeta, account, baos);
    }
    return fileMeta;
}

Этот код отлично работает для некоторых изображений, но не работает для большинства изображений. Кто-нибудь знает.

Например, для следующего изображения введите описание изображения здесьэто работает идеально, потому что я отлично получаю обрезанное изображение.

Но для этого изображения, например, введите описание изображения здесья неправильно получаю обрезанное изображение.


person Saurabh Kumar    schedule 29.07.2013    source источник
comment
Я удалял тег java, прежде чем действительно увидел, что java был включен в вопрос. Мне жаль. Я снова добавил java, но не смог сделать его первым тегом в списке.   -  person Anders Lindén    schedule 07.12.2015


Ответы (2)


Я использовал приведенный ниже код, и он работает для меня. Пожалуйста, просмотрите ниже.

Ваша проблема здесь:

setSelect: [0, 0, 150, 180],

который вы передаете постоянно

jQuery(function ($) {

        // Create variables (in this scope) to hold the API and image size
        var jcrop_api,
            boundx,
            boundy,

            // Grab some information about the preview pane
            $preview = $('#preview-pane'),
            $pcnt = $('#preview-pane .preview-container'),
            $pimg = $('#preview-pane .preview-container img'),

            xsize = $pcnt.width(),
            ysize = $pcnt.height();

        console.log('init', [xsize, ysize]);
        $('#target').Jcrop({
            onChange: updatePreview,
            onSelect: updatePreview,
            onSelect: storeCoords,
            aspectRatio: xsize / ysize,
            boxWidth: 350, boxHeight: 350
        }, function () {
            // Use the API to get the real image size
            var bounds = this.getBounds();
            boundx = bounds[0];
            boundy = bounds[1];
            // Store the API in the jcrop_api variable
            jcrop_api = this;

            // Move the preview into the jcrop container for css positioning
            $preview.appendTo(jcrop_api.ui.holder);
        });

        function updatePreview(c) {
            if (parseInt(c.w) > 0) {
                var rx = xsize / c.w;
                var ry = ysize / c.h;

                $pimg.css({
                    width: Math.round(rx * boundx) + 'px',
                    height: Math.round(ry * boundy) + 'px',
                    marginLeft: '-' + Math.round(rx * c.x) + 'px',
                    marginTop: '-' + Math.round(ry * c.y) + 'px'
                });
            }
            // storeCoords(c);
        };
        function storeCoords(c) {

            jQuery('#X').val(c.x);
            jQuery('#Y').val(c.y);
            jQuery('#W').val(c.w);
            jQuery('#H').val(c.h);


        };

    });

Пожалуйста, отделите эту функцию от вашего кода.

     function storeCoords(c) {

        jQuery('#X').val(c.x);
        jQuery('#Y').val(c.y);
        jQuery('#W').val(c.w);
        jQuery('#H').val(c.h);


    };

И поместите вызов storeCoords в свои фиксированные координаты, которые вы установили ранее, как

setSelect:storeCoords ,
person Janty    schedule 07.08.2013

Не имея журналов консоли, показывающих ошибки, которые потенциально могут идентифицировать проблему, вам придется согласиться с несоответствием, которое я обнаружил. Идентификационные теги должны использоваться строго только для одного элемента. Я вижу, что вы используете идентификационный тег, предположительно, для нескольких изображений. Это не соответствует требованиям HTML 5, поскольку идентификаторы предназначены только для одного объекта, а классы предназначены для нескольких объектов. Вы должны переключиться на класс и выполнить итерацию по объектам, которым назначен этот класс. Например:

$(".cropimages").each(function(index) {
  $(this).Jcrop({
    onChange: updateInfo,
    onSelect: updateInfo,
    onRelease: clearInfo,
    setSelect: [0, 0, 150, 180],
    boxWidth: 400, boxHeight: 300,
    allowMove: true, 
    allowResize: true, 
    allowSelect: true,
    aspectRatio: xsize / ysize
  }, function(){
    // Use the API to get the real image size
    var bounds = this.getBounds();
    boundx = bounds[0];
    boundy = bounds[1];
    // Store the API in the jcrop_api variable
    jcrop_api = this;

    // Move the preview into the jcrop container for css positioning
    $preview.appendTo(jcrop_api.ui.holder);
  });
});

С этим кодом убедитесь, что все ваши изображения используют класс cropimages. Это должно повторяться через каждый, а затем обрезать их. Также убедитесь, что у вас есть все необходимые библиотеки, и проверьте консоль на наличие ошибок.

person Clay Freeman    schedule 01.08.2013