Image Handpicked by JCrop User

Successfully implemented JCrop example code for selecting an area on an image with a preview and getting coordinates.

However, the challenge lies in allowing users to select an image from their file system, display it in the browser, and perform the aforementioned actions.

An attempt was made to replace the hardcoded image reference with a simple Javascript function. The standalone Javascript code functions well in enabling image selection and display in the browser.

Unfortunately, integrating this with the JQuery/JCrop code for image area selection and preview seems to be problematic.

The current code setup is as follows:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Aspect Ratio with Preview Pane | Jcrop Demo</title>
  <meta http-equiv="Content-type" content="text/html;charset=UTF-8" />

<script src="../js/jquery.min.js"></script>
<script src="../js/jquery.Jcrop.js"></script>
<script type="text/javascript">
  jQuery(function($){

    // Variables for API, image size, and preview pane info
    var jcrop_api,
        boundx,
        boundy,

        $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,
      aspectRatio: xsize / ysize
    },function(){
      var bounds = this.getBounds();
      boundx = bounds[0];
      boundy = bounds[1];
      jcrop_api = this;
      $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' 
        });
      }

      $('#x1').val(c.x);
      $('#y1').val(c.y);
      $('#x2').val(c.x2);
      $('#y2').val(c.y2);
      $('#w').val(c.w);
      $('#h').val(c.h);
    };

  });
</script>

<link rel="stylesheet" href="demo_files/main.css" type="text/css" />
<link rel="stylesheet" href="demo_files/demos.css" type="text/css" />
<link rel="stylesheet" href="../css/jquery.Jcrop.css" type="text/css" />
<style type="text/css">

.jcrop-holder #preview-pane {
  display: block;
  position: absolute;
  z-index: 2000;
  top: 75px;
  right: -270px;
  padding: 6px;
  border: 1px rgba(0,0,0,.4) solid;
  background-color: white;

  -webkit-border-radius: 6px;
  -moz-border-radius: 6px;
  border-radius: 6px;

  -webkit-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
  -moz-box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
  box-shadow: 1px 1px 5px 2px rgba(0, 0, 0, 0.2);
}

#preview-pane .preview-container {
  width: 170px;
  height: 170px;
  overflow: hidden;
}

</style>

</head>
<body>

<div class="container">
<div class="row">
<div class="span12">
<div class="jc-demo-box">

<div class="page-header">
<h1>Aspect Ratio with Preview Pane</h1>
</div>

  <input type = "file"  id = "src" />
  <img id="target" alt="[Jcrop Example]" />

  <div id="preview-pane">
    <div class="preview-container">
      <img id="target_preview" class="jcrop-preview" alt="Preview" />
    </div>
  </div>

  <script>
    function showImage(src,target,target_preview) {
            var fr=new FileReader();
            fr.onload = function(e) { 
                   target.src = this.result;
                    target_preview.src = this.result 
            };
            src.addEventListener("change",function() {
                fr.readAsDataURL(src.files[0]);
            });
    }

    var src = document.getElementById("src");
    var target = document.getElementById("target");
    var target_preview = document.getElementById("target_preview");
    showImage(src,target,target_preview);

  </script> 

  <form id="coords"
    class="coords"
    onsubmit="return false;"
    action="http://example.com/post.php">

    <div class="inline-labels">
    <label style="display: none">X1 <input type="text" size="4" id="x1" name="x1"/></label>
    <label style="display: none">Y1 <input type="text" size="4" id="y1" name="y1"/></label>
    <label style="display: none">X2 <input type="text" size="4" id="x2" name="x2"/></label>
    <label style="display: none">Y2 <input type="text" size="4" id="y2" name="y2"/></label>
    <label style="display: none">W <input type="text" size="4" id="w" name="w"/></label>
    <label style="display: none">H <input type="text" size="4" id="h" name="h"/></label>
    </div>
  </form>



<div class="clearfix"></div>

</div>
</div>
</div>
</div>

</body>
</html>

For this task, relevant Javascript is enclosed within the tags.

Referencing a related SO post that may provide insight: Input file show live selected image in JCrop

Exploring the use of JCrop's "setImage" function can be beneficial for achieving the desired outcome. Any guidance or additional information would be greatly appreciated. Thank you.

Answer №1

One effective approach is to pre-populate the database with images, then retrieve these images upon loading, organizing them into an array list of objects. Transform these images into StreamedContent using the byte[] obtained from the database, and display them within a PrimeFaces data table.

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

Enhance Your jQuery Skills by Adding Custom Directories to Anchor Links

Can jQuery be used to add a custom folder name in front of all links on a webpage? For example, if the website has these links: <a href="/user/login">Login</a> <a href="/user/register">Register</a> <a href="/user/forum">Foru ...

Setting environment variables using the node command is successful on Linux and macOS platforms, however, it may not function properly

When I clone a project using git, I encounter issues running npm run build on Windows. The command works fine on Mac and Linux: "build": "API=https://dev-api.myexample.com/v1.0 babel-node build.js", An error message is displayed: 'API' is no ...

Verifying Angular (2+?) Compatibility: Opening and Closing Material mat-menu on Hover [GUIDE]

After extensive research, I tried various methods to hover a material menu to display its options. However, the solutions I came across were either too complicated or ineffective. Therefore, I decided to develop my own solution by combining elements of e ...

Gallery and Endless Carousel with AJAX Integration

Utilizing the Galleria plugin for an image gallery on a page loaded within a frame using ajax. The following code snippet showcases how the AJAX functionality is implemented: $(document).ready(function() { function loadTab(pageUrl) { $.ajax( ...

Dynamic Dropdown Menu with AJAX, PHP, and jQuery

I am currently working with a file called ajax.php ' <?php class AJAX { private $database = NULL; private $_query = NULL; private $_fields = array(); public $_index = NULL; const DB_HOST = "localhost ...

Ways to prevent the input value from rising on a number type input when the up button is pressed

I'm curious about whether it's possible to prevent the input value from increasing when I press the up button on a type number input. Any ideas? ...

How to style the background color of the selected option in a <select> element using

Is there a specific style I can use to change the color of a selected option in a dropdown menu? For example: <HTML> <BODY> <FORM NAME="form1"> <SELECT NAME="mySelect" SIZE="7" style="background-color:red;"> <OPTION>Test 1 &l ...

Is it possible to replicate an HTML table using JavaScript without including the headers?

Discover a JavaScript snippet in this stack overflow post that allows you to create a button for automatically selecting and copying a table to the clipboard. When pasting the data into an Excel template, my users prefer not to include the header informat ...

The dropdown menu in Mantine is malfunctioning, even though I copied and pasted the exact code from

While following a tutorial, I encountered an issue with the Mantine Menu and Dropdown components. The tutorial creator did not wrap the React App inside the MantineProvider, which resulted in errors when trying to use the Dropdown component. Even after add ...

Merging two arrays concurrently in Angular 7

When attempting to merge two arrays side by side, I followed the procedure below but encountered the following error: Cannot set Property "account" of undefined. This is the code in question: acs = [ { "account": "Cash In Hand", ...

What is the most effective way to transfer color values from one div to another?

When recreating a game similar to Mastermind, I encountered a challenge of copying color values from one div to another upon clicking a button. Despite browsing the web, I haven't found a solution for this specific situation. Below is the code I have ...

How do I add a "Switch to Desktop Site" link on a mobile site that redirects to the desktop version without redirecting back to the mobile version once it loads?

After creating a custom mobile skin for a website, I faced an issue with looping back to the mobile version when trying to add a "view desktop version" link. The code snippet below detects the screen size and redirects accordingly: <script type="text/j ...

Executing a function to erase the stored value in local storage during an Angular unit test

Looking to verify whether the localStorage gets cleared when I execute my function. Component ngOnInit() { // Logging out when reaching login screen for login purposes this.authService.logout(); } authService logout() { // Removing logged i ...

The JavaScript alert box cannot retrieve data from the PHP parent page

What am I missing? Here is the JavaScript code snippet: <script language="javascript"> function openPopup(url) { window.open(url,'popupWindow','toolbar=no,location=no,directories=no,status=no, menubar=no,scrollbars=n ...

What is the best way to reference a div link from a different PHP file?

Struggling to access a page div from another php file, I've tried calling it using (found online) admin.php#changepass Here's an example of my HTML code: <div id="changepass" class="w3-container city" style="display:none"> <form name ...

Code for retrieving information; some data may not be retrieved

I created a Google Sheets script that iterates through all rows and retrieves API data, then pastes the results in a column all at once. Everything was working fine until I started using the following code snippet instead of referencing a sheet name. var s ...

Using Vue components in NativeScript-Vue popups: A comprehensive guide

To initiate the popup, I include the following code in a root component: import parentt from "./parentt.vue"; . . . this.$showModal(parentt, { fullscreen: true, }); The contents of parentt.vue are as follows: <template> <StackLayout> ...

Image remains fluid within a static div without resizing

Any assistance would be greatly appreciated. I am currently facing an issue with a fixed div that is floating at the bottom of the screen, serving as ad space for the mobile version of a website. The problem arises when attempting to resize the browser win ...

Utilize JSON data to display markers on Leaflet maps

I am exploring the world of Leaflet and I have a question about loading markers from a database into a leaflet map using PHP. In my PHP code, I extract latitude and longitude data from the database based on the selected ward and encode it in JSON format. ...

What is the best way to transfer data from an HTML input field to a PHP script?

Within my patient_display.php file, I am calling the patient_history.php script and passing along the P_ID. Here is an outline of my code. patient_display.php: echo '<form name="Patient" action="patient_history_display.php" method="get">'; ...