online mostrar leer imagen decodificar data convertir cargar binario archivo php image base64

php - mostrar - ¿Cómo convertir una imagen a codificación base64?



leer imagen base64 (9)

Aquí está el código para cargarlo para codificarlo y guardarlo en MySQL

if (!isset($_GET["getfile"])) { if ($_FILES["file"]["error"] > 0) { echo "Error: " . $_FILES["file"]["error"] . "<br>"; } else { move_uploaded_file($_FILES["file"]["tmp_name"], $_FILES["file"]["name"]); $bin_string = file_get_contents($_FILES["file"]["name"]); $hex_string = base64_encode($bin_string); $mysqli = mysqli_init(); if (!$mysqli->real_connect(''localhost'', ''root'', '''', ''arihant'')) { die(''Connect Error ('' . mysqli_connect_errno() . '') '' . mysqli_connect_error()); } $mysqli->query("INSERT INTO upload(image) VALUES (''" . $hex_string . "'')"); } }

Para mostrar la imagen usa este

echo "<img src=''data:image/jpeg;base64, $image'' width=300>";

¿Me pueden guiar, por favor, cómo puedo convertir una imagen de una URL a la codificación base64?


Aquí hay un ejemplo que usa una llamada cURL. Esto es mejor que la función file_get_contents () . Por supuesto, usa base64_encode ()

$url = "http://example.com"; $ch = curl_init($url); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_HEADER, 0); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); $output = curl_exec($ch); curl_close($ch); ?> <img src="data:image/png;base64,<?php echo base64_encode($output);?>">


Creo que debería ser:

$path = ''myfolder/myimage.png''; $type = pathinfo($path, PATHINFO_EXTENSION); $data = file_get_contents($path); $base64 = ''data:image/'' . $type . '';base64,'' . base64_encode($data);


En caso de que (por cualquier motivo) no pueda utilizar curl ni file_get_contents , puede file_get_contents :

$img = imagecreatefrompng(''...''); ob_start(); imagepng($img); $bin = ob_get_clean(); $b64 = base64_encode($bin);


Fácil:

$imagedata = file_get_contents("/path/to/image.jpg"); // alternatively specify an URL, if PHP settings allow $base64 = base64_encode($imagedata);

tenga en cuenta que esto aumentará los datos en un 33%, y tendrá problemas con los archivos cuyo tamaño exceda su límite de memory_limit .


Muy simple y de uso común:

function getDataURI($imagePath) { $finfo = new finfo(FILEINFO_MIME_TYPE); $type = $finfo->file($imagePath); return ''data:''.$type.'';base64,''.base64_encode(file_get_contents($imagePath)); } //Use the above function like below: echo ''<img src="''.getDataURI(''./images/my-file.svg'').''" alt="">''; echo ''<img src="''.getDataURI(''./images/my-file.png'').''" alt="">'';

Nota: El tipo Mime del archivo se agregará automáticamente (tomando la ayuda de esta documentación de PHP ).


También puede hacer esto a través de curl, solo necesita una ruta a un archivo de imagen y pasarlo a la función que se indica a continuación.

public static function getImageDataFromUrl($url) { $urlParts = pathinfo($url); $extension = $urlParts[''extension'']; $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); curl_setopt($ch, CURLOPT_HEADER, 0); $response = curl_exec($ch); curl_close($ch); $base64 = ''data:image/'' . $extension . '';base64,'' . base64_encode($response); return $base64; }


Utilice también esta forma de representar la imagen en formato de codificación base64 ... encuentre la función PHP file_get_content y, a continuación, utilice la función base64_encode

y obtenga el resultado para preparar str como data:" . file_mime_type . " base64_encoded string . data:" . file_mime_type . " base64_encoded string . Úsalo en el atributo img src. Vea el siguiente código, ¿puedo ayudarlo?

// A few settings $img_file = ''raju.jpg''; // Read image path, convert to base64 encoding $imgData = base64_encode(file_get_contents($img_file)); // Format the image SRC: data:{mime};base64,{data}; $src = ''data: ''.mime_content_type($img_file).'';base64,''.$imgData; // Echo out a sample image echo ''<img src="''.$src.''">'';


<img src="data:image/png;base64,<?php echo base64_encode(file_get_contents("IMAGE URL HERE")) ?>">

Estaba tratando de usar este recurso pero seguí recibiendo un error, encontré que el código anterior funcionó perfectamente.

Simplemente reemplace la URL de la IMAGEN AQUÍ con la URL de su imagen: http://www.website.com/image.jpg