简体   繁体   中英

PHP Convert A File to JPG

Currently, I learn about File To image encryption

first, I upload a file, for example testing.txt file then, I get the byte array from that file. then, from that byte array, I want to make a jpg file.

how to get byte array from file? and then make a jpg from byte array?

here my code:

//file to by array
$filename = "testing.txt"; 
$handle = fopen($filename, "rb"); 
$fsize = filesize($filename); 
$contents = fread($handle, $fsize); 
$byteArray = unpack("N*",$contents);

echo "<pre>";
print_r($byteArray); 
echo "</pre>";


// from byte array to jpg
$fp = fopen("result.jpg", "wb");
$len = count($byteArray);
for ($i = 1; $i <= $len; $i++)
{
    $data = pack("C*",$byteArray[$i]);
    fwrite($fp, $data);
}
fclose($fp);

thanks

This is an code example how you can convert text data into binary one and then pass it to image. As mentioned in comments above, png is a better option of doing this.

<?php
const CHARS = [
    'A', 'B', 'C', 'D', 'E',
    'F', 'G', 'H', 'I', 'J',
    'K', 'L', 'M', 'N', 'O',
    'P', 'Q', 'R', 'S', 'T',
    'U', 'V', 'W', 'X', 'Y',
    'Z', 'a', 'b', 'c', 'd',
    'e', 'f', 'g', 'h', 'i',
    'j', 'k', 'l', 'm', 'n',
    'o', 'p', 'q', 'r', 's',
    't', 'u', 'v', 'w', 'x',
    'y', 'z', '0', '1', '2',
    '3', '4', '5', '6', '7',
    '8', '9', '+', '/'
];

function charToInt($char) {
    return array_search($char, CHARS);
}

function textToBin($content) {
    $content_len = strlen($content);
    $bin = '';

    // Convert content into binary
    for ($a = 0; $a < $content_len; $a++) {
        $bin .= sprintf("%06d", decbin(charToInt($content[$a])));
    }

    // Fill rest of last chunk with zeros as padding and calculate offset
    $offset = 8 - (strlen($bin) % 8);
    $bin .= str_repeat("0", $offset);

    // Return binary string
    return $bin;
}

function makeImage($textFilePath) {
    //get text data and encode it to binary
    $data = base64_encode(file_get_contents($textFilePath));
    $binaryData = textToBin($data);

    //split binary data into 8 bit chunks
    $chunks = explode(" ", trim(chunk_split($binaryData, 8, " ")));

    // Add extra chunks to make total chuncks divisible by 3 for complete RGB pixels
    while (count($chunks) % 3 != 0) {
        $chunks[] = 0xFF;
    }
    // Calculate dimensions of image
    $dim = ceil(sqrt(count($chunks) / 3));
    $img = imagecreatetruecolor($dim, ceil(count($chunks) / $dim / 3));
    $colors = array();

    // Convert groups of 3 chunks into pixels
    for ($a = 0; $a < count($chunks); $a += 3) {
        array_push($colors, imagecolorallocate($img, bindec($chunks[$a]), bindec($chunks[$a+1]), bindec($chunks[$a+2])));
    }

    // Set color for each pixel
    for ($j = 0; $j < $dim; $j++) {
        for ($i = 0; $i < $dim; $i++) {
            @imagesetpixel($img, $i, $j, $colors[($j*$dim)+$i]);
        }
    }

    // Output image
    imagepng($img, 'output.png');
    imagedestroy($img);

}

makeImage($argv[1]);

Run php test.php <path to text file> to convert file and save it to output.png

If you want to hide a text in an Image set up this two files:

img.txt

Lorem ipsum dolor sit amet, cu vis assum mazim audiam, no everti recusabo mel. Facer hendrerit disputationi ei nam, ex nec vidit nonumes liberavisse. Oporteat qualisque eum id, vis semper vivendum vulputate at. Meis theophrastus vix in.

and

img.php

<?php

/**
 *
 * PHP Convert a Text-File to a PNG (and reverse)
 *
 * https://stackoverflow.com/q/51416394/5201919
 *
 * powered by adilbo.com
 *
 */

// HEADLINE TO BROWSER
echo '<pre><h1>PHP Convert a Text-File to a PNG (and reverse)</h1>';

// DEBUG INFOS TO BROWSER
echo '<h2>INPUT (img.txt)</h2><b>TEXT</b><br>';

// MAIN FUNCTION CALL TO WRITE TEXT TO IMAGE
$textInput = text2image( 'img.txt', 'img.png' );

// DEBUG INFOS TO BROWSER
echo $textInput . '<br><b>BINARY</b><br>';
echo implode( ' ', str_split( ascii2hex($textInput), 2) );
echo '<h2>OUTPUT (img.png)</h2>';
echo '<b>IMAGE (1x1 Pixel)</b><br>';
echo '<img border="1" src="img.png">';

// MAIN FUNCTION CALL TO GET TEXT FROM IMAGE
$textOutput = image2text( 'img.png' );

// DEBUG INFOS TO BROWSER
echo '<br><br><b>TEXT</b><br>' . $textOutput;
echo '<br><b>BINARY</b><br>';
echo implode( ' ', str_split( ascii2hex($textOutput), 2) );
echo '<br><br><b>"L o r e m" - Controll Values</b><br>';
echo strtoupper( dechex( ord( 'L' ) ) ) . ' ';
echo strtoupper( dechex( ord( 'o' ) ) ) . ' ';
echo strtoupper( dechex( ord( 'r' ) ) ) . ' ';
echo strtoupper( dechex( ord( 'e' ) ) ) . ' ';
echo strtoupper( dechex( ord( 'm' ) ) );

// HELPER FUNCTIONS
function ascii2hex( $ascii ) {

  // ini var
  $string = '';

  // loop string each digit
  for ($i = 0 ; $i < strlen( $ascii ) ; $i ++ ) {

    // convert ascii value to hex
    $byte = strtoupper( dechex( ord( substr( $ascii, $i, 1 ) ) ) );

    // add hex value two-digits
    $string .= str_repeat( '0', 2 - strlen( $byte ) ) . $byte;

  // end loop
  }

  // give back
  return $string;
}

function hex2ascii( $hex ) {

  // ini var
  $string = '';

  // loop string each two digits
  for ($i = 0 ; $i < strlen( $hex ) ; $i += 2 ) {

    // add each two digits hex2dec and then to ascii
    $string .= chr( hexdec( substr( $hex, $i, 2 ) ) );

  // end loop
  }

  // give back
  return $string;
}

function text2image( $textFilename, $imageFilename ) {

  // READ TEXT FILE TO STRING
  $string = file_get_contents( $textFilename );

  // OPEN PNG-IMAGE FOR WRITING DATA
  $fileHandl = fopen( $imageFilename, 'wb' );

  // WRITE PNG-IMAGE-PART
  fwrite( $fileHandl, hex2bin( '89504e470d0a1a0a0000000d494844520000000100000001010300000025db56ca00000003504c5445000000a77a3dda0000000174524e530040e6d8660000000a4944415408d76360000000020001e221bc330000000049454e44ae426082' ) );

  // WRITE CONVERTET DATA TO IMAGE FILE
  fwrite( $fileHandl, ascii2hex($string) );

  // CLOSE IMAGE FILE AFTER WRITING
  fclose( $fileHandl );

  // give back clear ascii text from file
  return $string;

}

function image2text( $imageFilename ) {

  // get image data (with offset of 95 chars for the PNG-Image Part)
  $binaryData = file_get_contents( 'img.png', FALSE, NULL, 95 );

  // convert data from hex to ascii string
  $text = hex2ascii( $binaryData );

  // give back
  return $text;

}

It will generate a transparent 1x1 Pixel PNG Image named img.png witch contain your text and you can also read the text from the image!

The Image is not so nice looking like from the answer from @DmytroZasiadko but also with a "read text from Image" function ;-)

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