Save the binary content of an image in the database

Asked

Viewed 6,499 times

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?

  • 7

    Bytecode image? Bytecode or binary content?

  • Does not serve the image saved temporarily on the hard drive, which comes by default? Simply store it in the BLOB, PHP discards the file itself if you don’t use the move_uploaded_file. I can get it from the STDIN, but then you’d have to sue her to separate from the rest of the multipart, which is much more complicated.

  • @Thomas bytecode even, would be more or less so but the inverse function http://answall.com/questions/5326/load-o-bytecode-da-imagem-em-string-e-converter-para-bitmap-no-flash-as3

  • 4

    Image does not normally have bytecode. Unless you’re talking about a virtual machine image ;) (bytecode refers to a pre-compiled intermediate code, which is neither the executable nor the source. common in Java, for example)

  • @Bacco take any image from your computer and click open with notepad, you know that bunch of strange characters it shows? then that’s what I want.

  • 1

    @This is the binary content of the image. Bytecode is something else.

  • I get it, you want the binary content of the image. Suggestion instead of the notepad use the Hxd (free), which it shows in hexadecimal, when you want to analyze a file. Anyway, as I commented, it would be easier to save from HD pro BLOB, or use STDIN. But remembering that by STDIN, if it comes by upload form, comes with a lot of "dirt" that will not be of your benefit.

  • @Bacco That kid, but I want to get this "binary content" with php, maybe using some command or library.

  • 1

    This takes everything the browser sent: http-get-request-body or this: $body = @file_get_contents('php://input');. Only it comes with headlines, boundaries, etc, and yet you would have to reverse the encoding of the data. Very boring to do. I still think it’s better to take it from the same hard drive, play in the BLOB and let PHP delete automatic (the speed is practically the same, and HD does not wear out so fast that you want to save recording and deletion). But let’s see if anyone who knows a lib ready-made.

  • @Bacco blz, but you think I should change the title and take bytecode and put something else in place?

  • Ah, I guess it doesn’t cost anything to get better, it’s technically more correct. Not that this is a serious problem, but since editing is simple, I think it fits. I just don’t understand yet what would be a good reason for you not to want to use the normal PHP method, but that’s another question. Returning to the issue of editing, it is good because comments on the subject will also be obsolete.

  • And if you use Base64 to convert the image?

  • Dude, turn on, you already have 3 answers that are valid and are giving downvote to everyone!!! I gave up to not demoralize who bothered to answer you >-(

  • @Andre I’m not following this question anymore, the downvotes are not mine... should be the guy who put my question in reward Lollipop

  • 1

    I edited for a new title more appropriate to the context.

Show 10 more comments

5 answers

1


If what you want is to simply save an image in BD, follow suggestion of how to do:

Listing 1: Table creation script in the database

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 saving the image in the database

<?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: http://www.devmedia.com.br/upload-de-imagens-em-php-e-mysql/10041

  • @Guilherme-birth the ideal is the use of mysqli_ or classes like PDO, for safety and performance reasons. Particularly I prefer the PDO, since I work with object-oriented programming. The above was only a transcription of the source mentioned, but the emphasis is on logic and not on methods.

  • Now that I saw that it was a link and not a question. I appreciate the link. But again I emphasize that I do not use mysql and much less write images in BD... just Gilizei for the partner to find something that would help him. But feel free to edit my answer ;)

  • Small improvements yes, change the code completely (as I suggest) I disagree, unless done by the author, who is you in the case. So the right case is to provide tips (which I’m not even doing)

  • I will list some suggestions: 1. Make error handling on fopen. 2. Do not use time() and do not save the file to the same script location, prefer to write to an isolated folder or /tmp 3. do not close the } else so, use this } else { ... }, if someone using the code misses a character an error may occur (prefer to standardize the typing style), read: http://answall.com/q/51002/3635

  • Thanks for the suggestions. I made some modifications. Others did not find it necessary since the goal is to give just an idea of how to write the image in BD, and not give all the code ready. ;)

  • As I said in another comment, here you should not necessarily just try to help the specific individual, but add content to the community, that is to make your response a useful source for the community and not just for one individual :) Another tip @ is not legal :( but I believe the answer is already acceptable, I hope you do not misunderstand me Good luck

Show 2 more comments

0

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

$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 synchronous large files can take a long time to be processed.

See more in at the source

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 database and use in HTML easily. However Base64 takes up 1/3 more space, that is, you will take up more disk space on your server and, more importantly, your page will take longer to load.

Utilizing:

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

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

  • Saving in base 64 is a nice move in this case, because Mysql supports the original data in a good way. You’re letting the file take up more space for nothing. It is even more wrong than addslashes (which is already an error too, mysql has specific escape function)

-1

After the POST is done, Voce takes the upload variable and saves the file any temporary folder, so you can read the file and save the content in the variable $image php to then save to 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 instead of addslashes (much used in internet examples), as it will facilitate later the display of the image in HTML, besides not changing the contents of the file.

Note that when using addslashes, function that returns a string with backslashes before characters that need to be escaped to be escaped in query the database, Voce will be changing the contents of the file.

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

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

-1

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

There are many things in the question. Uploading images to the server can be done using FTP software (Fetch, Cyber Duck...) or using the "upload" system (input type file, example here: http://php.net/manual/en/features.file-upload.post-method.php).

In the case of FTP vc puts the image (the document), where you want it. Then vc must indicate to 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 Moveupload file function (http://php.net/manual/en/function.move-uploaded-file.php) you should put the image in another folder.

The treatment: if the goal is only to solve a problem type "curiosity", I think better to send in FTP (but easy). Then read the image using fopen(), put the data into a "string" and insert into a BLOB.

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

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

Easier, but we can get in front of another problem: how 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: place in a "inaccessible" folder. This depends on the hosting you have, more on the hosting I have, I land put data "before" folder "www". Documents are invisible from the Web, but I can read them from PHP.

My opinion: well think the "why" before seeking the "how".

Browser other questions tagged

You are not signed in. Login or sign up in order to post.