Encode an image to base64 using a data: URI

@param image The image file
@return The base64 encoded value
@throws java.io.IOException java.io.IOException
198944
public static String toBase64(File image) throws IOException {
        return "data:" + MimeType.getByFilename(image.getName()) + ";base64," + BaseEncoding.base64().encode(IOUtils.toByteArray(image));
    }
921038
protected void prepareImageUrl(FacesContext context, StringBuffer results) throws IOException {

		String src = (String) getAttributes().get("src");
		boolean base64 = Boolean.parseBoolean((String) getAttributes().get("base64"));
		prepareAttribute(results, "src", getImageUrl(context, src, base64));
	}
164942
public static String imgToBase64Str(BufferedImage image, String formatName) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        String base64Str = null;
        try {
            ImageIO.write(image, formatName == null ? "jpeg" : formatName, baos);
            byte[] bytes = baos.toByteArray();
            base64Str = CommonUtils.bytesToBase64Str(bytes);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            CommonUtils.closeIOStream(null, baos);
        }
        return base64Str;
    }
1161559
public static boolean isKnownByteFormat( BufferedImage image ) {
		int type = image.getType();
		return type != BufferedImage.TYPE_BYTE_INDEXED &&
				type != BufferedImage.TYPE_BYTE_BINARY &&
				type != BufferedImage.TYPE_CUSTOM;
	}
818109
public static String encodeURL(String uri)
  {
    CharBuffer cb = CharBuffer.allocate();

    for (int i = 0; i < uri.length(); i++) {
      char ch = uri.charAt(i);

      switch (ch) {
      case '<':
      case '>':
      case ' ':
      case '%':
      case '\'':
      case '\"':
        cb.append('%');
        cb.append(encodeHex(ch >> 4));
        cb.append(encodeHex(ch));
        break;

      default:
        cb.append(ch);
      }
    }

    return cb.close();
  }
1164649
public static void saveImage(BufferedImage image, OutputStream output) throws IOException
    {
        ImageIO.write(image, "png", output);
    }
532570
def img_encode(arr, **kwargs):
    
    sio = BytesIO()
    imsave(sio, arr, **kwargs)
    sio.seek(0)
    img_format = kwargs['format'] if kwargs.get('format') else 'png'
    img_str = base64.b64encode(sio.getvalue()).decode()

    return 'data:image/{};base64,{}'.format(img_format, img_str)
1028989
public static BufferedImage toBufferedImage(final Image image) {
        if (image instanceof BufferedImage) {
            return (BufferedImage) image;
        }

        // Create a buffered image with transparency
        final BufferedImage bufferedImage =
                new BufferedImage(image.getWidth(null), image.getHeight(null), BufferedImage.TYPE_INT_ARGB);

        final Graphics2D bufferedGraphics = bufferedImage.createGraphics();
        bufferedGraphics.drawImage(image, 0, 0, null);
        bufferedGraphics.dispose();

        // Return the buffered image
        return bufferedImage;
    }
1313891
public static boolean canWrite (BufferedImage image)
    {
        return (image.getColorModel() instanceof IndexColorModel) &&
            (image.getRaster().getDataBuffer() instanceof DataBufferByte);
    }
541773
public static String encode(final String source) {
		if (source == null) {
			return null;
		}
		return encodeInToBase64(source.getBytes());
	}
1203713
private static String base64Encode(byte[] data) {
        char c64[] = new char[data.length * 4 / 3 + 5];
        for (int i = 0, k = 0; i < data.length; i += 3, k += 4) {
            c64[k + 0] = (char) (data[i] >> 2);
            c64[k + 1] = (char) ((data[i] & 0x03) << 4);
            c64[k + 2] = c64[k + 3] = 64;
            if ((i + i) < data.length) {
                c64[k + 1] |= data[i + 1] >> 4;
                c64[k + 2] = (char) ((data[i + 1] & 0x0f) << 2);
            }
            if ((i + 2) < data.length) {
                c64[k + 2] |= data[i + 2] >> 6;
                c64[k + 3] = (char) (data[i + 2] & 0x3f);
            }
            for (int j = 0; j < 4; ++j) {
                c64[k + j] = BASE64_LUT.charAt(c64[k + j]);
            }
        }
        return new String(c64);
    }
465577
public static String convertToBase64(String source) {
        if (source == null) {
            return null;
        }
        return Base64.encodeBase64URLSafeString(StringUtils.getBytesUtf8(source));
    }
279663
@Nonnull
  public static String rescaleImageAndEncodeAsBase64(@Nonnull final File file, final int maxSize) throws IOException {
    final Image image = ImageIO.read(file);
    if (image == null) {
      throw new IllegalArgumentException("Can't load image file : " + file); //NOI18N
    }
    return rescaleImageAndEncodeAsBase64(image, maxSize);
  }
1029778
public static BufferedImage base64StrToImg(String imgStr) {
        Base64.Decoder decoder = Base64.getDecoder();
        byte[] bytes = decoder.decode(imgStr);
        for (int i = 0; i < bytes.length; i++) {
            if (bytes[i] < 0) {
                bytes[i] += 256;
            }
        }
        ByteArrayInputStream bais = new ByteArrayInputStream(bytes);
        BufferedImage image = null;
        try {
            image = ImageIO.read(bais);
        } catch (IOException e) {
            throw new RuntimeException(e);
        } finally {
            CommonUtils.closeIOStream(bais, null);
        }
        return image;
    }
611140
@SuppressWarnings("UnusedDeclaration")
    private String createDataURI(final URL imageURL) {
        return imgCache.computeIfAbsent(imageURL, url -> {
            String dataUrl = null;
            try (final InputStream isGuess = url.openStream();
                 final InputStream isConvert = url.openStream();
                 final ByteArrayOutputStream os = new ByteArrayOutputStream()) {
                final String contentType = URLConnection.guessContentTypeFromStream(isGuess);
                if (null != contentType) {
                    final byte[] chunk = new byte[4096];
                    int bytesRead;
                    while ((bytesRead = isConvert.read(chunk)) > 0) {
                        os.write(chunk, 0, bytesRead);
                    }
                    os.flush();
                    dataUrl = "data:" + contentType + ";base64," + Base64.getEncoder().encodeToString(os
                            .toByteArray());
                } else {
                    if (logger.isWarnEnabled()) {
                        logger.warn("could not get content type from {}", imageURL.toExternalForm());
                    }
                }
            } catch (final IOException e) {
                if (logger.isWarnEnabled()) {
                    logger.warn("error loading image", e);
                }
            }
            if (null == dataUrl) {
                if (logger.isWarnEnabled()) {
                    logger.warn("could not create data url from {}", imageURL.toExternalForm());
                }
            }
            return dataUrl;
        });
    }
791616
String encodeBinary(byte[] data){
        if (data == null) return null;
        return Base64.encodeToString(data,Base64.URL_SAFE|Base64.NO_WRAP);
    }
1343427
function convertImageToBase64(image) {
  let fileReader = new FileReader();

  return new Promise( (resolve, reject) => {

    fileReader.onload = fileLoadedEvent => resolve(fileLoadedEvent.target.result);

    fileReader.readAsDataURL(image);

  });
}