Home > Backend Development > PHP Problem > How to convert files to binary output in PHP

How to convert files to binary output in PHP

藏色散人
Release: 2023-03-03 12:08:01
Original
5569 people have browsed it

PHP method to convert files to binary: first set "header("Content-type: image/jpeg");"; then open and read the file through the fopen and fread functions; finally convert the image file to binary Just output the stream to the client.

How to convert files to binary output in PHP

Recommended: "PHP Tutorial"

php converts files into binary output

header( "Content-type: image/jpeg");
$PSize = filesize('1.jpg');
$picturedata = fread(fopen('1.jpg', "r"), $PSize);
echo $picturedata;
Copy after login

With just a few words, the picture is output to the client in the form of a binary stream, which is no different from opening a picture. It should be noted that the header sent should be determined according to the specific situation. Not necessarily all image/jpeg. JPG is it, but PNG is image/png. Different pictures output different headers.

Purpose:

OSS supports uploading file streams by default, but the input form returns a file by default:

 /**
    * 支持文件类型上传到OSS
    */
    public static  function uploadFile($filename, $ext = 'jpg', $type = Enum_OSS_File_Type::IMG) {
        $content = static::file2content($filename);
        return static::upload($content, $ext, $type);
    }
    
    public static  function file2content($filename) {
        return fread(fopen($filename, 'r'), filesize($filename));
    }
Copy after login

The above is the detailed content of How to convert files to binary output in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template