php image file to base64

Выводим изображение в кодировке Base64 на HTML/CSS и сохраняем его на jQuery+PHP

Base64 – это некий стандарт кодирования информации посредством только 64 символов таблицы ASCII. В эту таблицу входят символы латинского языка (A-Z и a-z), цифры от 0 до 9, а также некоторые знаки.

Принцип этого кодирования – представление любой цифровой информации в виде уникального набора символов этой таблицы.

Чтобы вы наглядно понимали, что это такое, поясню. Перед вами изображение:

php image file to base64. Смотреть фото php image file to base64. Смотреть картинку php image file to base64. Картинка про php image file to base64. Фото php image file to base64

А вот его кодировка Base64:

Что нас здесь интересует? Как сохранить такие данные и представить их в читабельном виде на примере все тех же изображений.

Выводим изображение в формате Base64 на HTML/CSS

В HTML встраивание подобного рода кода осуществляется с помощью всем привычного тега IMG. И на примере все той же картинки результат будет следующим:

Помимо этого, Base64 можно встроить и в CSS-файл:

Какие есть преимущества у этой кодировки? Основное преимущество – это то, что изображения вы не храните на своем сервере и вообще ни на каком в принципе, а просто размещаете нужные вам файлы в теле страницы обычным текстом.

Сохранение изображения в формате Base64 на jQuery+PHP

Чуть выше мы разобрали с вами встраивание изображений непосредственно в страницу вашего сайта с помощью HTML и CSS, а сейчас мы рассмотрим способ сохранения такого изображения на вашем сайте.

В одной из статей был рассмотрен вопрос о том, как же сделать скриншот элемента на JavaScript, используя библиотеку html2canvas. В примере мы рассматривали скриншот как уже готовое изображение, но мы не упомянули, что при использовании там кода:

можно получить изображение как раз в кодировке Base64.

Давайте попробуем сохранить это (вы можете использовать свое) изображение в кодировке Base64, используя технологию AJAX и не большой PHP-скрипт.

Начнем с jQuery. Скрипт, который будет посылать в обработчик (PHP-скрипт) наши данные, будет выглядеть следующим образом:

Где «base_image» – данные изображения в Base64, «/upload/base-image.php» – путь до PHP-скрипта, а «#result» – ID элемента, в который будет выводиться результат.

Сам же скрипт-обработчик будет выглядеть следующим образом:

Здесь все предельно просто – получаем данные, обрабатываем и сохраняем их в той же директории, что и сам обработчик.

В качестве функции запуска я использовал обычную загрузку страницы, вы же можете привязать ее, например, к клику по ссылке или другому нужному вам действию.

Расписал вроде все максимально подробно, но если какие-то моменты вызывают у вас трудности, не стесняйтесь и задавайте их в комментариях – никого не оставим без внимания.

Источник

PHP: create image with ImagePng and convert with base64_encode in a single file?

I have created an image with ImagePng(). I dont want it to save the image to the file system but want to output it on the same page as base64 encode inline Image, like

which does not work.

Is this possible in a single PHP file at all?

3 Answers 3

This is adapted from a user example in the imagepng() docs.

php image file to base64. Смотреть фото php image file to base64. Смотреть картинку php image file to base64. Картинка про php image file to base64. Фото php image file to base64

I had trouble using the ob_get_contents() when using PHP with AJAX, so I tried this:

This saves a temporary image file on the server and then it is removed after it is encoded and echoed out.

php image file to base64. Смотреть фото php image file to base64. Смотреть картинку php image file to base64. Картинка про php image file to base64. Фото php image file to base64

If you do not wish to store to an explicit file, and you are already using ob_start() for something else (so you cannot use ob_start for this case without a lot of refactoring), you can define your own stream wrapper that store a stream output to a variable.

Not the answer you’re looking for? Browse other questions tagged php image gd or ask your own question.

Linked

Related

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

site design / logo © 2021 Stack Exchange Inc; user contributions licensed under cc by-sa. rev 2021.9.17.40238

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

base64_decode

(PHP 4, PHP 5, PHP 7, PHP 8)

base64_decode — Декодирует данные, закодированные MIME base64

Описание

Список параметров

Возвращаемые значения

Возвращает декодированные данные или false в случае возникновения ошибки. Возвращаемые данные могут быть бинарными.

Примеры

Пример #1 Пример использования base64_decode()

Результат выполнения данного примера:

Смотрите также

User Contributed Notes 17 notes

If you want to save data that is derived from a Javascript canvas.toDataURL() function, you have to convert blanks into plusses. If you do not do that, the decoded data is corrupted:

Base64 for URL parameters/filenames, that adhere to RFC 4648.
Defaults to dropping the padding on encode since it’s not required for decoding, and keeps the URL free of % encodings.

The base64-decoding function is a homomorphism between modulo 4 and modulo 3-length segmented strings. That motivates a divide and conquer approach: Split the encoded string into substrings counting modulo 4 chars, then decode each substring and concatenate all of them.

This function supports «base64url» as described in Section 5 of RFC 4648, «Base 64 Encoding with URL and Filename Safe Alphabet»

To follow up on Starson’s post, PHP was changed to no longer treat a space as if it were a plus sign in CVS revision 1.43.2.1, which corresponds to PHP 5.1.0. You can see what happened with a diff to branch point 1.43 at:

The CVS log indicates that this change was made to fix bug #34214 (base64_decode() does not properly ignore whitespace).

It would seem from the comment preceding the code which was removed that the treatment of the space as if it were the plus sign was actually intentional at one time:

When Base64 gets POSTed, all pluses are interpreted as spaces.
This line changes them back. It’s not exactly the Base64 spec,
but it is completely compatible with it (the spec says that spaces
are invalid). This will also save many people considerable
headache.

However, RFC 3548 states that characters not in the Base64 alphabet should either be ignored or cause the implementation to reject the encoding and RFC 2045 says they should be ignored. So the original code was unfortunately not fully compatible with the spec or other implementations. It may have also masked problems with code not properly escaping POST variables.

Источник

Base 64 encode vs loading an image file

So I am working on something in php where I have to get my images from a sql database where they will be encoded in base64. The speed of displaying these images is critical so I am trying to figure out if it would be faster turn the database data into an image file and then load it in the browser, or just echo the raw base64 data and use:

Which is supported in FireFox and other Gecko browsers.

So to recap, would it be faster to transfer an actual image file or the base64 code. Would it require less http request when using ajax to load the images?

The images would be no more than 100 pixels total.

10 Answers 10

Well I don’t agree with anyone of you. There are cases when you’ve to load more and more images. Not all the pages contain 3 images at all. Actually I’m working on a site where you’ve to load more than 200 images. What happens when 100000 users request that 200 images on a very loaded site. The disks of the server, returning the images should collapse. Even worse you’ve to make so much request to the server instead of one with base64. For so much thumbnails I’d prefer the base64 representation, pre-saved in the database. I found the solution and a strong argumentation at http://www.stoimen.com/2009/04/23/when-you-should-use-base64-for-images/. The guy is really in that case and made some tests. I was impressed and make my tests as well. The reality is like it says. For so much images loaded in one page the one response from the server is really helpful.

Why regenerate the image again and again if it will not be modified. Hypothetically, even if there are a 1000 different possible images to be shown based on 1000 different conditions, I still think that 1000 images on the disks are better. Remember, disk based images can be cached by the browser and save bandwidth etc etc.

It’s a very fast and easy solution. Although the image size will increase about 33% in size, using base64 will reduce significantly the number of http requests.

Google images and Yahoo images are using base64 and serving images inline. Check source code and you’ll see it.

Of course there are drawbacks on this approach, but I believe the benefits outweighs the costs. A cons I have found is in slow devices. For example, In iPhone 3GS the images served by google images are very slow to render, since the images come gziped from the server and must be uncompressed in the browser. So, if the customer has a slow device, he will suffer a little when rendering the images.

To answer the initial question, I ran a test measuring a jpeg image 400×300 px in 96 ppi:

I have used base64 images once or twice for icons (10×10 pixels or so).

Base64 images pros:

Base64 images cons:

Normal images pros:

Don’t think data:// works in IE7 or below.

When an image is requested you could save it to the filesystem then serve that from then on. If the image data in the database changes then just delete the file. Serve it from another domain too like img.domain.com. You can get all the benefits of last-modified, or e-tags for free from your webserver without having to start up PHP unless you need too.

If you’re using apache:

Generally, using base64 encoding is going to increase the byte size by about 1/3. Because of that, you are going to have to move 1/3 bytes from the database into the server, and then move those extra same 1/3 bytes over the wire to the browser.

Of course, as the size of the image grows, the overhead mentioned will increase proportionately.

That being said, I think it is a good idea to change the files into their byte representations in the db, and transmit those.

A few things, from several answers

Google images and Yahoo images are using base64 and serving images inline. Check source code and you’ll see it.

No. They absolutely do NOT. Images are mostly served from a static file «web server» Specfically gstatic.com: e.g. https://ssl.gstatic.com/gb/images/p1_2446527d.png

So actually, No advantage at all, plus the processing needed to compress?

page is retrieved in single request. Again, multiple parallel requests as opposed to a single larger load.

What happens when 100000 users request that 200 images on a very loaded site. The disks of the server, returning the images should collapse. You will still be sending The same amount of data, but having a Longer connection time, as well as stressing your database. Secondly the odds of a run of the mill site having 100000 concurrent connections. and even if so, if you are running this all of a single server you are a foolish admin.

Forward planning? You can only scale up so far, and scaling a DB is expensive (relatively speaking). Again the disks you say will «sp

In such a case, where you are serving 100’s of images to 100000 concurrent users, the serving of you images should be the domain of CDN Object store.

Источник

Detecting image type from base64 string in PHP

Is it possible to find out the type of an image encoded as a base64 String in PHP?

I have no method of accessing the original image file, just the encoded string. From what I’ve seen, imagecreatefromstring() can create an image resource from a string representation (after it’s been decoded from base64), but it automatically detects the image type and the image resource itself is a special PHP representation. In case I want to save the image as a file again, I would have no idea if the type I am saving it as corresponds to the original type from which the String representation was created.

7 Answers 7

FileInfo can do that for you:

If you dont want to use these functions because of their dependencies you can use the first bytes of the data:

The solution given by @Marc B is the best one for me (if our php version is > 5.3.0 otherwise we can use the solution given by @Aaron Murgatroyd).

I would like to give a little addition to this solution.

To get the image type you can do it like this :

Hope that can help someone and thanks to @Marc B for his solution.

For an exhaustive list of mime type you can look here :

The way shown by @Marc B is the nicest.

Should FInfo not be available, the only other way I know is to store the data into a file, and run a getimagesize() on it.

php image file to base64. Смотреть фото php image file to base64. Смотреть картинку php image file to base64. Картинка про php image file to base64. Фото php image file to base64

If you know a minimal amount about the file format structure, you could theoretically look at the top bytes of the file until you could work out what type of file it is.

Likewise, PNG files have the string PNG fairly near the start (it’s not quite at the very begining; again, you’d need to research the file format specifics to help you determine how much you’d need to know to be certain).

Getting the file format definitions would definitely give you more accuracy, but depending on how accurate you need to be, you might learn enough about the files formats just by opening some image files in a binary editor to see how they’re structured.

Источник

Добавить комментарий

Ваш адрес email не будет опубликован. Обязательные поля помечены *