BLOB type images stored in a table

2

Does anyone know how to extract BLOB type images stored in a MySQL table and convert them to .png, to store them in a folder?

The following code extracts the image of the "200x150" field from the "img_alq" table and displays it on the screen:

<?php
header("Content-type: image/png"); 

if(isset($_GET['id'])){   
    $id = $_GET['id']; 

    $link = mysql_connect("localhost", "root", "") or die ("ERROR AL CONECTAR"); 
    $db_select = mysql_select_db('claromec_restore') or die ("ERROR al seleccionar la BD");

    $sql = "SELECT *
                    FROM 'img_alq' 
                    WHERE 'idalq' = $id
                    ORDER BY 'idalq' ASC, 'orden' ASC, 'id' ASC";

    $result = mysql_query($sql, $link) or die ("Error al consultar"); 


    while ($row = mysql_fetch_assoc($result)) { 
    echo $row["200x150"]; 
    } 


    mysql_free_result($result); 
    } else { 
        echo 'NO hay ID'; 
 } 

?>
    
asked by Ricardo Pastuszek 27.05.2017 в 15:48
source

1 answer

1

Display an image that was saved as BLOB

1. Show directly as a result of the request

Having been saved in its original format, it is only necessary to show it as a result of the request:

if ($row = mysql_fetch_assoc($result)) { 
    $imagen = $row["200x150"];

    header("Content-type: image/jpeg");
    echo $imagen;


    die(); //No debería haber más salida
}
  • Note that only a single image is shown, so it is not appropriate to loop the results of the query to the base.


2. Show within an HTML

It can be displayed inside a% tag <img> , coded in base 64.

<img src="data:image/jpeg;base64,<?php 
    echo base64_encode( $imagen ); 
?>" />


3. Convert or manipulate the image before displaying it

For handling images in PHP, the functions GD offer an immediate solution for what you need .

In this case, imagecreatefromstring () generates an image resource, which we can then convert, modify as desired, or save to a new file.

if ($row = mysql_fetch_assoc($result)) { 
    $imagen = $row["200x150"];

    //Crear el recurso de imagen desde un string binario
    $imagenGD = imagecreatefromstring( $imagen );

    if ( $imagenGD ) {
        header("Content-type: image/png");
        //Mostrar como PNG
        imagepng( $imagenGD );
    } else {
        //Error con la imagen
    }
    imagedestroy( $imagenGD ); //liberar el recurso
}
  • If instead of displaying the image as a result of the HTTP request, you would like to save it in a new file, it would be passing the route as the second parameter:

    imagepng( $imagenGD, $nombreArchivo );
    
answered by 27.05.2017 / 19:12
source