


Let'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.
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
- ##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
- # The
##File (
File
) interface provides information about a file and allows JavaScript in web pages to access its contents. File document entryFor example
2. 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 falsePS: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.
PHP Video TutorialRecommended learning: "
"
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!

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

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.

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

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

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

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

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.

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


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

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

Hot Article

Hot Tools

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
Small size, syntax highlighting, does not support code prompt function

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

ZendStudio 13.5.1 Mac
Powerful PHP integrated development environment

PhpStorm Mac version
The latest (2018.2.1) professional PHP integrated development tool
