Skip to content

Instantly share code, notes, and snippets.

@k4zuki02h4t4
Last active May 10, 2022 07:30
Show Gist options
  • Save k4zuki02h4t4/a831467f31a62f6568fe905a1beefdde to your computer and use it in GitHub Desktop.
Save k4zuki02h4t4/a831467f31a62f6568fe905a1beefdde to your computer and use it in GitHub Desktop.
[WordPress] Attachment image to base64
<?php
/**
* Attachment image to base64
*
* @package WordPress
* @subpackage VA Attachment image to base64
* @author KUCKLU <kuck1u@visualive.jp>
* Copyright (C) 2015 KUCKLU and VisuAlive.
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
if ( ! defined( 'ABSPATH' ) ) {
exit;
}
class VisuAlive_AttachmentImage_To_Base64 {
/**
* Get instance.
*
* @since VisuAlive 1.0.0
* @return VisuAlive_AttachmentImage_To_Base64
*/
public static function init() {
static $instance = false;
if ( ! $instance ) {
$instance = new VisuAlive_AttachmentImage_To_Base64;
}
return $instance;
}
public function __construct() {
add_filter( 'wp_update_attachment_metadata', [ &$this, 'wp_update_attachment_metadata' ], 10, 2 );
add_filter( 'image_downsize', [ &$this, 'image_downsize' ], 10, 3 );
add_filter( 'wp_calculate_image_srcset_meta', [ &$this, 'wp_calculate_image_srcset_meta' ], 10, 4 );
add_filter( 'wp_calculate_image_srcset', [ &$this, 'wp_calculate_image_srcset' ], 10, 5 );
add_filter( 'tiny_mce_before_init', [ &$this, 'tiny_mce_enable_base64_images' ] );
}
/**
* Change attachment metadata.
*
* @param array $data Array of updated attachment meta data.
*
* @return array
*/
public function wp_update_attachment_metadata( $data = [ ], $post_ID ) {
$mime_types = self::_image_mime_types();
$file_type = isset( $data['file'] ) ? self::_check_filetype( $data['file'] ) : null;
$post_meta = $data;
if ( ! is_null( $file_type ) && in_array( $file_type, $mime_types ) ) {
$upload_dir = wp_upload_dir();
$img_path_original = $upload_dir['basedir'] . DIRECTORY_SEPARATOR . $post_meta['file'];
if ( file_exists( $img_path_original ) ) {
$base64_original = self::_image_to_base64( $img_path_original, $file_type );
if ( ! is_null( $base64_original ) ) {
$post_meta['file'] = $base64_original;
}
foreach ( $post_meta['sizes'] as $size => $value ) {
$img_path_child = $upload_dir['path'] . DIRECTORY_SEPARATOR . $value['file'];
if ( file_exists( $img_path_child ) ) {
$base64_child = self::_image_to_base64( $img_path_child, $value['mime-type'] );
if ( ! is_null( $base64_child ) ) {
$post_meta['sizes'][ $size ]['file'] = $base64_child;
}
}
}
}
}
update_post_meta( $post_ID, '_va_attachment_image_to_base64', $post_meta );
return $data;
}
/**
* Change attachment data.
*
* @param bool $file
* @param int $id
* @param string|array $size
*
* @return array
*/
public function image_downsize( $file, $id, $size ) {
$metas = self::_get_attachment_metadata( $id );
$site_icon_id = get_option( 'site_icon' );
if ( ! isset( $metas, $metas['sizes'] ) || empty( $metas ) || (int) $site_icon_id === (int) $id ) {
return $file;
}
if ( isset( $metas['sizes'][ $size ] ) ) {
$check = self::_confirm_an_image_is_base64( $metas['sizes'][ $size ]['file'] );
if ( $check ) {
$file = [
$metas['sizes'][ $size ]['file'],
$metas['sizes'][ $size ]['width'],
$metas['sizes'][ $size ]['height'],
true,
];
}
} else {
$check = self::_confirm_an_image_is_base64( $metas['file'] );
if ( $check ) {
$file = [
$metas['file'],
$metas['width'],
$metas['height'],
true,
];
}
}
return $file;
}
public function wp_calculate_image_srcset_meta( $image_meta, $size_array, $image_src, $attachment_id ) {
return self::_get_attachment_metadata( $attachment_id );
}
/**
* Filter an image's 'srcset' sources.
*
* @param array $sources
* @param array $size_array Array of width and height values in pixels (in that order).
* @param string $image_src The 'src' of the image.
* @param array $image_meta The image meta data as returned by 'wp_get_attachment_metadata()'.
* @param int $attachment_id Image attachment ID or 0.
*
* @return array
*/
public function wp_calculate_image_srcset( $sources, $size_array, $image_src, $image_meta, $attachment_id ) {
$upload_dir = wp_upload_dir();
if ( is_array( $sources ) && ! empty( $sources ) ) {
foreach ( $sources as $key => $value ) {
$sources[ $key ]['url'] = str_replace( trailingslashit( $upload_dir['baseurl'] ), '', $value['url'] );
}
}
return $sources;
}
/**
* [TinyMCE] Enable base64 images.
*
* @param array $settings
*
* @return array
*/
public function tiny_mce_enable_base64_images( $settings ) {
$settings['paste_data_images'] = true;
return $settings;
}
/**
* Confirm an image is base64.
*
* @param string $file
*
* @return bool
*/
protected function _confirm_an_image_is_base64( $file = '' ) {
return (bool) preg_match( '/(data:(image\/jpeg|image\/png|image\/gif|image\/bmp);base64,)/i', $file );
}
/**
* Mime types.
*
* @return array
*/
protected function _image_mime_types() {
return [ 'image/jpeg', 'image/png', 'image/gif', 'image/bmp' ];
}
/**
* Check file type.
*
* @param string $file
*
* @return string
*/
protected function _check_filetype( $file = '' ) {
$file = wp_check_filetype( $file, wp_get_mime_types() );
return $file['type'];
}
/**
* Retrieve attachment meta field for attachment ID.
*
* @param int $post_id Attachment ID. Default 0.
* @param bool $unfiltered Optional. If true, filters are not run. Default false.
*
* @return mixed Attachment meta field. False on failure.
*/
protected function _get_attachment_metadata( $post_id = 0, $unfiltered = false ) {
$post_id = (int) $post_id;
if ( ! $post = get_post( $post_id ) ) {
return false;
}
$data = get_post_meta( $post->ID, '_va_attachment_image_to_base64', true );
if ( $unfiltered ) {
return $data;
}
/**
* Filter the attachment meta data.
*
* @param array|bool $data Array of meta data for the given attachment, or false
* if the object does not exist.
* @param int $post_id Attachment ID.
*/
return apply_filters( 'va_get_attachment_metadata', $data, $post->ID );
}
/**
* Image to base64.
*
* @param string $image_path
* @param string $mime_type
*
* @return null|string
*/
protected function _image_to_base64( $image_path = '', $mime_type = '' ) {
$result = null;
$mime_types = self::_image_mime_types();
if ( file_exists( $image_path ) && in_array( $mime_type, $mime_types ) ) {
$result = base64_encode( file_get_contents( $image_path ) );
$result = 'data:' . $mime_type . ';base64,' . $result;
}
return $result;
}
}
@k4zuki02h4t4
Copy link
Author

k4zuki02h4t4 commented Jun 3, 2016

現在確認出来ている不具合

  • カスタムヘッダーの URL がテーマオプションに保存されない
  • サイトアイコンの URL が出力されない

不具合ではなく仕様

  • カスタムヘッダーの URL は Data URI にはならない。

@k4zuki02h4t4
Copy link
Author

やればやるほどハマる orz
wp_update_attachment_metadata で書き換えないで、素直に meta data として別途保存した方が幸せになれそう。

@k4zuki02h4t4
Copy link
Author

なんとか形になった。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment