Save in the database the binary content of an image

9

How do I get the bytecode of an image at upload time to be able to store it in the mysql blob field without the need to save the image to ftp?

    
asked by anonymous 04.12.2014 / 15:50

5 answers

3

If you just want to save an image in BD, here's how to do it:

Listing 1: Database creation script

CREATE TABLE PESSOA (  
    PES_ID int NOT NULL AUTO_INCREMENT PRIMARY KEY,  
    PES_IMG BLOB  
);

Listing 2: Upload form

<form action="gravar.php" method="POST" enctype="multipart/form-data"> 
    <label for="imagem">Imagem:</label> 
    <input type="file" name="imagem"/> <br/> 
    <input type="submit" value="Enviar"/> 
</form>

Listing 3: Script to write the image to the bank

<?php 
$imagem = $_FILES["imagem"]; 
$host = "localhost"; 
$username = "root"; 
$password = ""; 
$db = "test"; 

$acesso = 'mysql:host=' . $host . ';db=' . $db; 

// Recebeu a imagem
if($imagem != NULL):
    $nomeFinal = time().'.jpg'; 

    // Tenta gravar o arquivo no servidor
    if (move_uploaded_file($imagem['tmp_name'], $nomeFinal)): 

        // Pega a imagem
        $tamanhoImg = filesize($nomeFinal); 
        $mysqlImg = addslashes(fread(fopen($nomeFinal, "r"), $tamanhoImg)); 

        // Conecta-se ao BD e tenta gravar
        try{
            $pdoConecta = new PDO( $acesso, $username, $password ) ;
            $pdoConecta->query("INSERT INTO PESSOA (PES_IMG) VALUES ('$mysqlImg')");
        } catch( PDOException $e ) {
            echo $e->getMessage();
        }

        // Apaga o arquivo
        unlink($nomeFinal); 
    endif;

else:
    echo"Você não realizou o upload de forma satisfatória."; 
endif;
?>

Source : link

    
18.02.2015 / 20:12
1

Well, if what you want is the byte array to save in the bank here's how to do it:

$filename = "myFile.sav"; 
$handle = fopen($filename, "rb"); 
$fsize = filesize($filename); 
$contents = fread($handle, $fsize); 
$byteArray = unpack("N*",$contents); 
print_r($byteArray); 
for($n = 0; $n < 16; $n++)
{ 
    echo $byteArray [$n].'<br/>'; 
}

But remember how php is sync large files can take a long time to process.

See more at at the source

    
17.12.2014 / 13:12
1

"How do I get the bytecode of an image at upload time so I can store it in the mysql blob field without saving the image to ftp ? "

The question has several things. Sending images to the server can be done using FTP software (Fetch, Cyber duck ...) or use the system of "upload" (input type file, example here: link ).

In the case of FTP you put the image (the document), wherever you want it. Then you should tell PHP where the image is, to do the treatment.

In the case of "upload", the server places the image in a "tmp" folder. Using the PHP function MoveUpload file ( link ) you should put the image in another folder.

The treatment: If the objective is only to solve a problem like "curiosity", I think it is better to send in FTP (easier). Then, read the image using fopen (), put the data in a string and INSERT a BLOB.

If the purpose and "use", is different. A BLOB is not "inside" the table, but it is a "document" outside the table, this means that SQL should open this document (and slow). Also, if you have a table with BLOB for images, when you are going to try to do SELECT *, you will certainly use more memory than SQL. And the result will also be slow.

What we do, usually and only put the "path" to get the image. For example "my_pict.jpg" in a Varchar.

Easier, but we can get in front of another problem: how to do to put my image but prevent the use of this image from another server? (another web site that wants to use my image without authorization for example). Op 1: put an htaccess that prevents reading Op 2: Put in an "unreachable" folder. This depends on the hosting you have, the more in the hosting that I have, I landing put "before" the "www" folder. The documents are invisible from the Web, but I can read them from PHP.

My opinion: well think the "why" before looking for the "how".

    
18.02.2015 / 21:33
0

What you're looking for is not binary, it's base64 .

With this function you can transform the image into a format that you can save in the bank and use in HTML easily. However, base64 occupies 1/3 more space, meaning you will take up more disk space on your server, and more importantly, your page will take longer to load.

Usage:

$imgEmBase64 = base64_encode($_FILES['nomeDoCampo']['tmp_name']);
$sql = "insert into banco (imagem) values( '" . mysql_real_escape($imgEmBase64). "')";
mysql_query($sql);

You can also transform this data into image files and save it to the server, but then it would be easier to accept the same image upload.

    
27.04.2015 / 19:23
0

After you have done POST, you will get the upload variable and save the file to any temporary folder, so you can read the file and save the content in the $ image variable of php for later you save in the database (MySQL BLOB type field).

<?php
           $path = "images/arquivo_temporario";
           if (move_uploaded_file($_FILES['imagem'][['tmp_name'], $path))
            {
                $handle = fopen($path, "r");
                $content = fread($handle, $size);
                $imagem = base64_encode($content);
                fclose($handle);
            }
?>

Notice that the base64_encode function was used instead of addslashes (much used in internet examples), since it will later facilitate the display of the HTML image, change the contents of the file.

Note that when you use addslashes , a function that returns a backslashed string before characters that need to be escaped to query database escaping, you are changing the content of file.

Once saved in the database, you can read the saved image and save it in the $ image variable of php to display it with the following HTML code with PHP:

<img src="data:image/jpeg;base64,<?php echo $imagem;?>"
    
27.06.2016 / 08:25