Utilizing Jcrop to Crop an Image that has been Uploaded

Currently, I am working on cropping an uploaded image using Jcrop. My goal is to enable the user to crop the image upon uploading it without storing the original image on the server. Instead, only the cropped part selected by the user via Jcrop will be saved to the server. You can view the issue on this fiddle link.

The code I have implemented is as follows:

HTML:

<form id="form1">
    <input type='file' id="imgInp" />
    <img id="blah" class="crop" src="#" alt="your image" />
    <input type="hidden" id="x" name="x" />
        <input type="hidden" id="y" name="y" />
        <input type="hidden" id="w" name="w" />
        <input type="hidden" id="h" name="h" />
</form>

CSS:

<style>
#blah {
    background-color: #FFF;
    width: 500px;
    height: 330px;
    font-size: 24px;
    display: block;
  }
</style>

Js:

function readURL(input) {
        if (input.files && input.files[0]) {
            var reader = new FileReader();

            reader.onload = function (e) {
                $('#blah').attr('src', e.target.result);
            }

            reader.readAsDataURL(input.files[0]);
        }
    }

    $("#imgInp").change(function(){
        console.log(this);
        readURL(this);
         $(function(){

    $('.crop').Jcrop({

      onSelect: updateCoords,

            bgOpacity:   .4,
            setSelect:   [ 100, 100, 50, 50 ],
            aspectRatio: 16 / 9
    });

  });
    });

  function updateCoords(c)
  {
    console.log(c);
    $('#x').val(c.x);
    $('#y').val(c.y);
    $('#w').val(c.w);
    $('#h').val(c.h);
  };

My approach has been to use the same image for JCrop after upload so that I can obtain coordinate values necessary for generating the final image. However, I am encountering a problem where the cropped area appears black instead of displaying the uploaded image. I would appreciate any insights on what might be wrong with the code.

Answer №1

The issue with the image appearing black is due to the call to jCrop being made before the image has fully loaded. To resolve this, you can move the call to jCrop after the reader.onload function so that it runs only after the image has finished loading. Here's an example:

reader.onload = function (e) {
     $('#image').attr('src', e.target.result);
     $('.crop').Jcrop({       
         onSelect: updateCoords,
         bgOpacity:   .4,
         setSelect:   [ 100, 100, 50, 50 ],
         aspectRatio: 16 / 9
      });
}

For a working example, check out this updated JSFiddle

Answer №2

It appears that Jcrop has not been updated in quite some time and lacks support for IE 11. One drawback is that it does not perform the actual image cropping itself. Instead, it provides you with coordinates which you must then upload along with the original images to the web server for cropping.

You may want to consider looking into a solution discussed here. This method offers the option of using the Jcrop & Upload plugin to crop, resize, and scale images directly in the browser before uploading them to the server. By utilizing the HTML 5 Canvas element, this plugin enables image cropping while also providing support for IE 11.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

How to Insert <ul></ul> After Every Other <li> Element Using Angular's ngRepeat

With my current setup, I have a list item (li) within a list (ul) and applied ngRepeart. However, I would like to create a new ul after every 2nd li. Is this possible with AngularJS? <ul> <li>simth</li> <li>aryan</li> < ...

The Bootstrap table is not adhering to the specified width when the display is set

I encountered an issue starting yesterday. I am utilizing Bootstrap 4 and tables. Whenever I set a width greater than 13.5vw, the table does not adjust accordingly. You can view the fiddle here Below is the code snippet: HTML <table cl ...

Consistently encountering errors when trying to install npm

While attempting to install the Search git whodotheyserve. com application, I encountered a persistent error that shows up regardless of what troubleshooting steps I take. I have experimented with different versions of npm, all of which are successfully in ...

The Mean stack seems to be having trouble posting to MongoDB as it is not producing any results, and no errors are being generated

I'm running into some issues with my code and could use some assistance. My goal is to create a post using inputted data, and when the button is clicked, it should be posted and saved in mongoDB. Here's what I have so far. Any help would be great ...

Viewing margins displayed differently in Chrome compared to Firefox and making corrections accordingly

Why is the margin not displaying correctly? I noticed a 4px difference in Chrome in the box_news element. I read something about rest.css but I'm not sure if it will be helpful in my situation. This is the code on the right side: <div class="righ ...

Converting an Ajax request from JavaScript to jQuery

I am new to Ajax and trying to convert an ajax request from javascript to jquery without success. Here is the javascript code snippet I am working with: function aaa(track_id) { var req = new XMLHttpRequest(); req.open("get", "list.php?tr=" + track_id, ...

HTML links have been disabled

I have been making updates to the charity website I manage, heroinitiative.org. You can view the revamp progress here: (please note that this is not live code, it is simply for my boss to see the progress and does not need to be kept secret, hence why I a ...

How to remove excess whitespace from a Bootstrap 4 title

https://i.sstatic.net/aib65.png I need help removing the white space between Table Title and Sub Titles. Additionally, I want "Sub1" along with the icon to be left-aligned within the cell <div class="mdc-layout-grid__cell stretch-card mdc-l ...

Navigate to a unique component

I am attempting to navigate to the location of a custom component, but the reference to it is not returning a valid HTML node. The function "goToContactUs" should execute this action. What would be the most effective approach to accomplish this? class H ...

What is the best way to generate a search link after a user has chosen their search criteria on a webpage?

In my search.html file, I have set up a form where users can input their search criteria and click the search button to find information within a database of 1000 records. The HTML part is complete, but I am unsure how to create the action link for the for ...

What is the best way to run JavaScript using nodriver in Python?

I'm currently facing some roadblocks while writing Python code. To elaborate, I've successfully logged into a site protected by Cloudflare using nodriver, and have been able to display the values of elements on the page. However, my ultimate obje ...

Python script to extract the link to a JavaScript file from the href tag in an HTML

Imagine a website similar to the following: This particular website contains links to pdf files referenced by an href tag in the page source, for example: <a href="javascript:$('form_cofo_pdf_view_B000114563.PDF').submit();">B000114563.PD ...

Is it possible to include pseudo element elements in the configuration of a custom theme in Material UI?

Within my file themeConfig.js, I have defined several theme variables that are utilized to style different components throughout my application. Among these variables, there is a need for implementing the -webkit scrollbar styles for certain components. Du ...

Encountering an issue with a basic jQuery custom function

Here is the code snippet that I am using: $(document).ready(function() { $.fn.addRemoveButton = function() { alert(1); }; $.addRemoveButton(); }); When I run this code, I encounter the following error in Firebug: TypeError: $.addRem ...

Executing action in PHP script simultaneously with Ajax

My JavaScript skills are a bit rusty, and I need help adding a "delete" feature to some code that displays rows of data. The code includes PHP, jQuery, and other JS elements. Here's the snippet: <?php require_once '../../app/Mage.php'; M ...

"The website seems to be experiencing some technical difficulties on Firefox, but I have switched to

I attempted to reset the text area after sending a message with the code below: $(document).keypress(function (e) { if (e.which == 13) { e.preventDefault(); var $form = $('#f1'); $.ajax({ url: $form.attr( ...

Mastering Angular's ngFor directive allows for powerful manipulation of arrays in the front-end

My goal is to use the last n elements from the orbit array, a task easily achieved with | slice: -n. However, I am facing an issue where in each iteration, I not only need access to the respective item but also its successor. The problem lies in the fact t ...

CSS styles not detected after device orientation change

I'm encountering an issue with my CSS styling for a layout in landscape mode on mobile devices. The styling works perfectly when the page is loaded in landscape mode, but if I load it in portrait mode and then change the orientation to landscape, the ...

The generation of the page fails due to the absence of defined data

Every time I try to start my server, the error message pops up saying 'data is not defined', even though I have already defined the data content. export default class App extends Component { data = [ { key: "john", val ...

Troubleshooting and analyzing the performance of web workers

When running computations like path-finding in web workers, it can take several seconds and optimizing it is crucial. I've noticed that Chrome is roughly 3 times faster for my current code, but I'm not sure where exactly the time is being spent o ...