Quantcast
Channel: Active questions tagged javascript - Stack Overflow
Viewing all articles
Browse latest Browse all 140762

Crop uploaded image in shiny with croppie.js and save as jpeg

$
0
0

I'd like to add simple cropping feature to my shiny app, where uploaded images can be cropped and saved to the file system.

The first part of uploading an image and rendering with croppie.js works, but I cannot get the second part of cropping and saving cropped image to www/ folder on button click to work.

The first problem is that the JS variable basic can not be referenced anymore in the second JS Code block. And even if, I do not know how I could use the variable croppedImage then to save the image as a jpeg file to the www folder.

library(shiny)
library(shinyjs)
library(stringr)

ui <- fluidPage(
  shinyjs::useShinyjs(),
  tags$head(HTML('<link href="https://cdnjs.cloudflare.com/ajax/libs/croppie/2.4.0/croppie.css" rel="stylesheet">')),
  tags$script(src = "https://ajax.googleapis.com/ajax/libs/jquery/2.1.4/jquery.min.js"),
  tags$script(src = "https://cdnjs.cloudflare.com/ajax/libs/croppie/2.4.0/croppie.js"),
  fileInput("image_upload",
            label = "Image", width = "300px",
            accept = c("image/png", "image/jpeg", "image/jpg")),
  div(id = "demo-basic", style = "
    width: 900px;
    height: 600px;"),
  br(),
  br(),
  actionButton("crop", "Crop image")
)

server <- function(input, output, session) {
  observeEvent(input$image_upload, {

    file.rename(input$image_upload$datapath, str_c("www/image0.jpg"))

    runjs(paste0("
                $(function () {
                  var basic = $('#demo-basic').croppie({
                viewport: {
                  width: 900,
                  height: 600
                }
        });
          basic.croppie('bind', {
            url: 'image0.jpg'
          });
    });
    "))
  })

  observeEvent(input$crop, {
    ## what I want is:
    ## - crop image and save in www/ folder, e.g. as image0_cropped.jpg
    runjs("
        console.log('button clicked');
        basic.croppie('result', {
                format: 'jpeg'
            }).then(function(croppedImage) {
                console.log('cropped');
            });
    ")
  })
}

shinyApp(ui, server)

Viewing all articles
Browse latest Browse all 140762

Latest Images

Trending Articles



Latest Images

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>