search
HomeBackend DevelopmentPHP TutorialLet's talk about the mutual conversion methods of Base64, Blob and File in PHP

This article brings you relevant knowledge about php. It mainly talks about how Base64, Blob and File are converted to each other? Friends who are interested can take a look below. I hope it will be helpful to everyone.

Let's talk about the mutual conversion methods of Base64, Blob and File in PHP

Preface

When obtaining pictures, I encountered a situation where I needed to convert the format, so I recorded it and shared it.

Text

1. Basic introduction to the format

  • Base64

Base64 is one of the most common encoding methods for transmitting 8Bit bytecode on the Internet. Base64 is a method of representing binary data based on 64 printable characters Base64 Document Entry

For example

Lets talk about the mutual conversion methods of Base64, Blob and File in PHP

  • ##Blob

##Blob

object represents an immutable, raw data file-like object. Its data can be read in text or binary format, or converted into ReadableStream for data operations. Blob document entry

For example

Lets talk about the mutual conversion methods of Base64, Blob and File in PHP

##File
    # The
  • ##File (

  • File

) interface provides information about a file and allows JavaScript in web pages to access its contents. File document entryFor example

#I won’t introduce too much, mainly about how to convert.

Lets talk about the mutual conversion methods of Base64, Blob and File in PHP2. How to judge these three formats

1. Determine whether it is a Base64 string

// 判断是否为base64格式字符串
function isBase64(str) {
    //正则表达式判断
    var reg = /^\s*data:([a-z]+\/[a-z0-9-+.]+(;[a-z-]+=[a-z0-9-]+)?)?(;base64)?,([a-z0-9!$&',()*+;=\-._~:@\/?%\s]*?)\s*$/i;
    return reg.test(str) //返回 true or false
}

2. Determine whether it is a Blob object

console.log(data instanceof Blob)   //ture  or  false

3 .Determine whether it is a File object

console.log(data instanceof File && !data instanceof Blob)   //ture  or  false

PS:

Both Blob and File use instanceof to determine whether it is the corresponding type of data

One thing to note is that the File object is also a Blob object , because File inherits from Blob, the judgment logic can be defined by yourself
3. Conversion between formats

1. Convert Base64 to File

function dataURLtoFile(dataurl, filename) {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new File([u8arr], filename, { type: mime });
}

You need to pass two parameters, the first is data, the second is a custom file name string

  • 2.Base64 conversion For Blob
function dataURLtoBlob(dataurl, filename) {
    var arr = dataurl.split(','),
        mime = arr[0].match(/:(.*?);/)[1],
        bstr = atob(arr[1]),
        n = bstr.length,
        u8arr = new Uint8Array(n);
    while (n--) {
        u8arr[n] = bstr.charCodeAt(n);
    }
    return new Blob([u8arr], { type: mime });
}

is basically the same as transferFile

, except for the last sentence
    return
  • 3.Blob to File
function blobToFile(blob) {
    return new File([blob], 'screenshot.png', { type: 'image/jpeg' })
}

Here and

Base64 to File
    are actually the
  • new File()

    method. , the second parameter above is passed in. It is fixed here. This parameter is not very important. You can modify the function by yourself. The methods have been provided, so you can use it directly. Recommended learning: "

    PHP Video Tutorial
  • "

The above is the detailed content of Let's talk about the mutual conversion methods of Base64, Blob and File in PHP. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:juejin. If there is any infringement, please contact admin@php.cn delete
PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

How to make PHP applications fasterHow to make PHP applications fasterMay 12, 2025 am 12:12 AM

TomakePHPapplicationsfaster,followthesesteps:1)UseOpcodeCachinglikeOPcachetostoreprecompiledscriptbytecode.2)MinimizeDatabaseQueriesbyusingquerycachingandefficientindexing.3)LeveragePHP7 Featuresforbettercodeefficiency.4)ImplementCachingStrategiessuc

PHP Performance Optimization Checklist: Improve Speed NowPHP Performance Optimization Checklist: Improve Speed NowMay 12, 2025 am 12:07 AM

ToimprovePHPapplicationspeed,followthesesteps:1)EnableopcodecachingwithAPCutoreducescriptexecutiontime.2)ImplementdatabasequerycachingusingPDOtominimizedatabasehits.3)UseHTTP/2tomultiplexrequestsandreduceconnectionoverhead.4)Limitsessionusagebyclosin

PHP Dependency Injection: Improve Code TestabilityPHP Dependency Injection: Improve Code TestabilityMay 12, 2025 am 12:03 AM

Dependency injection (DI) significantly improves the testability of PHP code by explicitly transitive dependencies. 1) DI decoupling classes and specific implementations make testing and maintenance more flexible. 2) Among the three types, the constructor injects explicit expression dependencies to keep the state consistent. 3) Use DI containers to manage complex dependencies to improve code quality and development efficiency.

PHP Performance Optimization: Database Query OptimizationPHP Performance Optimization: Database Query OptimizationMay 12, 2025 am 12:02 AM

DatabasequeryoptimizationinPHPinvolvesseveralstrategiestoenhanceperformance.1)Selectonlynecessarycolumnstoreducedatatransfer.2)Useindexingtospeedupdataretrieval.3)Implementquerycachingtostoreresultsoffrequentqueries.4)Utilizepreparedstatementsforeffi

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

MantisBT

MantisBT

Mantis is an easy-to-deploy web-based defect tracking tool designed to aid in product defect tracking. It requires PHP, MySQL and a web server. Check out our demo and hosting services.

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download

VSCode Windows 64-bit Download

A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool