简体   繁体   中英

Image Editor + AJAX - Base64

I am implementing an image editor with the cutting tool and upload via Ajax.

Image Editor: http://codepen.io/bigaton/pen/NRBKaa

var cropper;
        document.querySelector('#file').addEventListener('change', function(){
            var reader = new FileReader();
            reader.onload = function(e) {
                options.imgSrc = e.target.result;
                cropper = new cropbox(options);
            }
            reader.readAsDataURL(this.files[0]);
            this.files = [];
        })

Upload via Ajax: https://github.com/rafaelcouto/Post1334

The conversion of the image to base64 and image editor blob restricts me to a picture of 500px (error on the server side) while the upload via Ajax the conversion is done differently and more efficiently, which can send resolution files higher (using the same upload code without errors).

My question is how to integrate the two codes: use the cutting tool 1 and the format conversion tool 2.

Problem solved. Instead of sending the base64 string by HTML POST (where I carried the string in a hidden field), dispatch of AJAX POST.

   document.querySelector('#btnCrop').addEventListener('click', function(){
   var img = cropper.getDataURL()
   $.post('ajax/salvar2.asp', {imagem: img});

This entry can be used in PHP and ASP.

Example base64 save in ASP image. (Salvar2.asp)

base64String = Trim(Request.Form("imagem"))
Set tmpDoc = Server.CreateObject("MSXML2.DomDocument")
Set nodeB64 = tmpDoc.CreateElement("b64")
nodeB64.DataType = "bin.base64"
nodeB64.Text = Mid(base64String, InStr(base64String, ",") + 1)
set bStream = server.CreateObject("ADODB.stream")
bStream.type = 1
call bStream.Open()
call bStream.Write(nodeB64.NodeTypedValue)
caminho=Server.MapPath("../caminho_salvaer/imagem.png")
call bStream.SaveToFile(caminho, 2)
call bStream.close()
set bStream = nothing

salvar.php

<?php

// Recuperando imagem em base64
// Exemplo: data:image/png;base64,AAAFBfj42Pj4
$imagem = $_POST['imagem'];

// Separando tipo dos dados da imagem
// $tipo: data:image/png
// $dados: base64,AAAFBfj42Pj4
list($tipo, $dados) = explode(';', $imagem);

// Isolando apenas o tipo da imagem
// $tipo: image/png
list(, $tipo) = explode(':', $tipo);

// Isolando apenas os dados da imagem
// $dados: AAAFBfj42Pj4
list(, $dados) = explode(',', $dados);

// Convertendo base64 para imagem
$dados = base64_decode($dados);

// Gerando nome aleatório para a imagem
$nome = md5(uniqid(time()));

// Salvando imagem em disco
file_put_contents("../img/{$nome}.jpg", $dados);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM