• We just launched and are currently in beta. Join us as we build and grow the community.

Cropping an Image before Saving using JS, jQuery, and PHP Tutorial

Abboud1245

Digital Asset Preservation Specialist
A Rep
0
0
0
Rep
0
A Vouches
0
0
0
Vouches
0
Posts
193
Likes
17
Bits
2 MONTHS
2 2 MONTHS OF SERVICE
LEVEL 1 200 XP
Introduction

In this tutorial, I will show you How to Crop an Image before Saving it using JS, jQuery, and JS Library. We can achieve this kind of feature for our web application by using Croppie Library. The tutorial aims to provide the student and new programmers a reference to learn with to enhance and develop their programming skills using JavaScript and PHP Language. Here, snippets and sample source codes are provided.

How to Crop Image before Saving it

There are a lot of options to Crop an Image in web development. This feature is usually created using JavaScript to allow the end-users to crop the image on the client side. We can create this kind of feature by using DOM Manipulation, event listeners, and some other method or object that are available in JavaScript. Writing code for this might be time-consuming and not easy, especially for beginners. But, with the help of Croppie Library, we can achieve this kind of feature without hassle.

What is Croppie Library?

Croppie Library is a JavaScript Library that was developed by Foliotek. This library comes with JavaScript and CSS files. It was mainly created to crop an image using JavaScript. You can download this library at https://github.com/Foliotek/Croppie/releases.

How to use Croppie Library?

Here are some snippets of using the Croppie Library to crop an Image before saving it in your web server. The said library comes with multiple options and methods that you can use.

Here's a basic example of using the Library

  1. var

    $croppie =

    new

    Croppie(

    $(

    '#croppie-element'

    )

    [

    0

    ]

    ,

    {
  2. boundary:

    {

    width:

    400

    ,

    height:

    400

    }

    ,
  3. viewport:

    {
  4. height:

    300

    ,
  5. width:

    300

    ,
  6. type:

    'square'
  7. }

    ,
  8. }

    )

The script above is only initializing the Cropping Feature to the specific element in your web page or HTML page. It will create a container and field where you can edit or crop your chosen image.

To bind an Image to the library. You can use the following snippet.

  1. $croppie.bind

    (

    {
  2. url:

    "sample_img.png"

    ,
  3. }

    )

    ;

The script above will bind your chosen image to the cropper element where you can adjust the image and select the part of the image to crop.

After you finish cropping the image, you can get the cropped image using the result method of the library. You can choose the format of the image (PNG, JPEG, WEBP) and select the type of result you want ('canvas', 'html', 'blob', or, 'rawcanvas'). Here's the following example to do it.

  1. $croppie.result

    (

    'blob'

    )

    .then

    (

    function

    (

    blob)

    {
  2. // do something here and use blob variable to get the cropped image result
  3. }

    )

    ;

Example

Here's a sample application that demonstrates how to crop images before saving them using Croppie Library, jQuery, Ajax, and PHP. This application allows users to upload and crop images. The browsed or chosen image can be also rotated clockwise or counterclockwise. Users can also resize the cropping container.

Interface

index.php

  1. <!DOCTYPE html>
  2. <html

    lang

    =

    "en"

    >
  3. <head

    >
  4. <meta

    charset

    =

    "UTF-8"

    >
  5. <meta

    http-equiv

    =

    "X-UA-Compatible"

    content

    =

    "IE=edge"

    >
  6. <meta

    name

    =

    "viewport"

    content

    =

    "width=device-width, initial-scale=1.0"

    >
  7. <title

    >

    Crop Image using Croppie JS</

    title

    >

  8. <link

    rel

    =

    "stylesheet"

    href

    =

    "https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"

    integrity=

    "sha384-Zenh87qX5JnK2Jl0vWa8Ck2rdkQ2Bzep5IDxbcnCeuOxjzrPF/et3URy9Bv1WTRi"

    crossorigin=

    "anonymous"

    >
  9. <link

    rel

    =

    "stylesheet"

    href

    =

    "./croppie/croppie.css"

    >
  10. <script

    src

    =

    "https://code.jquery.com/jquery-3.6.1.min.js"

    integrity=

    "sha256-o88AwQnZB+VDvE9tvIXrMQaPlFFSUTR+nldQm1LuPXQ="

    crossorigin=

    "anonymous"

    ></

    script

    >
  11. <script

    src

    =

    "https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"

    integrity=

    "sha384-OERcA2EqjJCMA+/3y+gxIOqMEjwtxJY7qPCqsdltbNJuaOe923+mo//f6V8Qbsw3"

    crossorigin=

    "anonymous"

    ></

    script

    >
  12. <script

    src

    =

    "./croppie/croppie.js"

    ></

    script

    >
  13. <style

    >
  14. html, body{
  15. min-height:100%;
  16. width:100%;
  17. }
  18. .img-holder {
  19. width: calc(100%);
  20. height: 30vh;
  21. background: black;
  22. }
  23. .img-holder img{
  24. object-position:
  25. }
  26. .img-holder img {
  27. width: calc(100%);
  28. height: calc(100%);
  29. object-fit: scale-down;
  30. object-position: center center;
  31. }
  32. </

    style

    >
  33. </

    head

    >
  34. <body

    >
  35. <nav class

    =

    "navbar navbar-expand-lg navbar-dark bg-primary bg-gradient"

    >
  36. <div

    class

    =

    "container"

    >
  37. <a

    class

    =

    "navbar-brand"

    href

    =

    "./"

    >

    Crop Image using Croppie JS</

    a

    >
  38. <div

    >
  39. <a

    href

    =

    "https://sourcecodester.com"

    class

    =

    "text-light fw-bolder h6 text-decoration-none"

    target

    =

    "_blank"

    >

    SourceCodester</

    a

    >
  40. </

    div

    >
  41. </

    div

    >
  42. </

    nav>
  43. <div

    class

    =

    "container-fluid px-5 my-3"

    >
  44. <div

    class

    =

    "clearfix my-3"

    ></

    div

    >
  45. <div

    class

    =

    "row"

    >
  46. <div

    class

    =

    "col-lg-6"

    >
  47. <div

    class

    =

    "card rounded-0"

    >
  48. <div

    class

    =

    "card-body rounded-0"

    >
  49. <form

    action

    =

    "upload.php"

    method

    =

    "POST"

    enctype

    =

    "multipart/form-data"

    >
  50. <div

    class

    =

    "col-lg-6 col-md-8 col-sm-12 mx-auto"

    >
  51. <div

    class

    =

    "mb-3"

    >
  52. <label

    for

    =

    "upload"

    class

    =

    "form-label"

    >

    Upload File</

    label

    >
  53. <input

    class

    =

    "form-control"

    type

    =

    "file"

    name

    =

    "upload"

    accept

    =

    "image/jpeg, image/png"

    id

    =

    "upload"

    >
  54. </

    div

    >
  55. </

    div

    >
  56. </

    form

    >
  57. <div

    id

    =

    "croppie-editor"

    class

    =

    "d-none"

    >
  58. <div

    id

    =

    "croppie-field"

    ></

    div

    >
  59. <div

    class

    =

    "mx-0 text-center"

    >
  60. <button

    class

    =

    "btn btn-sm btn-light border border-dark rounded-0"

    id

    =

    "rotate-left"

    type

    =

    "button"

    >

    Rotate Left</

    button

    >
  61. <button

    class

    =

    "btn btn-sm btn-light border border-dark rounded-0"

    id

    =

    "rotate-right"

    type

    =

    "button"

    >

    Rotate Right</

    button

    >
  62. <button

    class

    =

    "btn btn-sm btn-primary rounded-0"

    id

    =

    "upload-btn"

    type

    =

    "button"

    >

    Upload</

    button

    >
  63. </

    div

    >
  64. </

    div

    >
  65. </

    div

    >
  66. </

    div

    >
  67. </

    div

    >
  68. <div

    class

    =

    "col-lg-6"

    >
  69. <div

    class

    =

    "card round-0 rounded-0"

    >
  70. <div

    class

    =

    "card-body rounded-0"

    >
  71. <div

    class

    =

    "container-fluid"

    >
  72. <div

    class

    =

    "d-flex flex-wrap"

    >
  73. <?php
  74. $dir =

    "uploads/"

    ;
  75. if(

    is_dir(

    $dir)

    )

    :
  76. $scandir =

    scandir(

    $dir)

    ;
  77. foreach(

    $scandir as $img)

    :
  78. if(

    in_array(

    $img, [

    '.'

    , '..'

    ]

    )

    )
  79. continue;
  80. ?>
  81. <div

    class

    =

    "col-lg-4 col-md-6 col-sm-12 p-1"

    >
  82. <div

    class

    =

    "position-relative img-holder"

    >
  83. <img

    src

    =

    "<?= $dir.$img ?>

    " alt="">
  84. </

    div

    >
  85. </

    div

    >
  86. <?php endforeach; ?>
  87. <?php endif; ?>
  88. </

    div

    >
  89. </

    div

    >
  90. </

    div

    >
  91. </

    div

    >
  92. </

    div

    >
  93. </

    div

    >
  94. </

    div

    >
  95. <script

    src

    =

    "app.js"

    ></

    script

    >

  96. </

    body

    >
  97. </

    html

    >

JavaScript

app.js

  1. var

    $croppie =

    new

    Croppie(

    $(

    '#croppie-field'

    )

    [

    0

    ]

    ,

    {
  2. enableExif:

    true

    ,
  3. enableResize:

    true

    ,
  4. enableZoom:

    true

    ,
  5. boundary:

    {

    width:

    400

    ,

    height:

    400

    }

    ,
  6. viewport:

    {
  7. height:

    300

    ,
  8. width:

    300
  9. }

    ,
  10. enableOrientation:

    true
  11. }

    )
  12. $(

    document)

    .ready

    (

    function

    (

    )

    {
  13. var

    img_name;
  14. // console.log($croppie)
  15. $(

    '#upload'

    )

    .on

    (

    'change'

    ,

    function

    (

    e)

    {
  16. var

    reader =

    new

    FileReader(

    )

    ;
  17. img_name =

    e.target

    .files

    [

    0

    ]

    .name

    ;
  18. reader.onload

    =

    function

    (

    e)

    {
  19. $croppie.bind

    (

    {
  20. url:

    e.target

    .result
  21. }

    )

    ;
  22. $(

    '#croppie-editor'

    )

    .removeClass

    (

    'd-none'

    )
  23. }
  24. reader.readAsDataURL

    (

    this

    .files

    [

    0

    ]

    )

    ;
  25. }

    )


  26. $(

    '#rotate-left'

    )

    .click

    (

    function

    (

    )

    {
  27. $croppie.rotate

    (

    90

    )

    ;
  28. }

    )
  29. $(

    '#rotate-right'

    )

    .click

    (

    function

    (

    )

    {
  30. $croppie.rotate

    (

    -

    90

    )

    ;

  31. }

    )
  32. $(

    '#upload-btn'

    )

    .click

    (

    function

    (

    )

    {
  33. $croppie.result

    (

    {
  34. type:

    'base64'

    ,
  35. format:

    'png'
  36. }

    )

    .then

    (

    (

    imgBase64)

    =>

    {
  37. $.ajax

    (

    {
  38. url:

    'save_image.php'

    ,
  39. method:

    'POST'

    ,
  40. data:

    {

    'img'

    :

    imgBase64,

    'fname'

    :

    img_name }

    ,
  41. dataType:

    'json'

    ,
  42. error:

    err =>

    {
  43. console.error

    (

    err)
  44. }

    ,
  45. success:

    function

    (

    response)

    {
  46. if

    (

    response.status

    ==

    'success'

    )

    {
  47. alert(

    "Cropped Image has been saved successfully."

    )
  48. location.reload

    (

    )
  49. }

    else

    {
  50. console.error

    (

    response)
  51. }
  52. }
  53. }

    )
  54. }

    )
  55. }

    )
  56. }

    )

Saving the Cropped Image

save_image.php

  1. <?php

  2. extract

    (

    $_POST

    )

    ;
  3. $dir

    =

    "uploads/"

    ;
  4. if

    (

    !

    is_dir

    (

    $dir

    )

    )
  5. mkdir

    (

    $dir

    )

    ;
  6. $img

    =

    str_replace

    (

    'data:image/png;base64,'

    ,

    ''

    ,

    $img

    )

    ;
  7. $img

    =

    str_replace

    (

    ' '

    ,

    '+'

    ,

    $img

    )

    ;
  8. $img

    =

    base64_decode

    (

    $img

    )

    ;
  9. $save

    =

    file_put_contents

    (

    $dir

    .

    $fname

    ,

    $img

    )

    ;
  10. if

    (

    $save

    )

    {
  11. $resp

    [

    'status'

    ]

    =

    'success'

    ;
  12. }

    else

    {
  13. $resp

    [

    'status'

    ]

    =

    'failed'

    ;

  14. }
  15. echo

    json_encode

    (

    $resp

    )

    ;

Snapshot

Here's the snapshot of the result of the source code I provided above.

I also provided the full source code zip file of the sample application on this website. You can download it by clicking the download button below this article. Leave a comment below with any questions you might want to ask regarding this tutorial.

That's it! I hope this Cropping Images before Saving Tutorial will help you with what you are looking for and that you'll find this useful for your current future web application projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding :)


Download
You must upgrade your account or reply in the thread to view hidden text.
 

442,401

317,942

317,951

Top