001/* 002 * Licensed to the Apache Software Foundation (ASF) under one or more 003 * contributor license agreements. See the NOTICE file distributed with 004 * this work for additional information regarding copyright ownership. 005 * The ASF licenses this file to You under the Apache License, Version 2.0 006 * (the "License"); you may not use this file except in compliance with 007 * the License. You may obtain a copy of the License at 008 * 009 * http://www.apache.org/licenses/LICENSE-2.0 010 * 011 * Unless required by applicable law or agreed to in writing, software 012 * distributed under the License is distributed on an "AS IS" BASIS, 013 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 014 * See the License for the specific language governing permissions and 015 * limitations under the License. 016 */ 017package org.apache.wicket.util.image; 018 019import java.io.IOException; 020import java.io.InputStream; 021import java.util.Base64; 022 023import org.apache.wicket.request.resource.PackageResourceReference; 024import org.apache.wicket.util.io.IOUtils; 025import org.apache.wicket.util.resource.IResourceStream; 026import org.apache.wicket.util.resource.ResourceStreamNotFoundException; 027 028/** 029 * Util class to provide basic image functionality like converting image data to base64 content 030 * 031 * @author Tobias Soloschenko 032 * @since 6.20.0 033 * 034 */ 035public class ImageUtil 036{ 037 038 /** 039 * Creates a base64 encoded image string based on the given image reference 040 * 041 * @param imageReference 042 * the image reference to create the base64 encoded image string of 043 * @param removeWhitespaces 044 * if whitespaces should be removed from the output 045 * @return the base64 encoded image string 046 * @throws ResourceStreamNotFoundException 047 * if the resource couldn't be found 048 * @throws IOException 049 * if the stream couldn't be read 050 */ 051 public static CharSequence createBase64EncodedImage(PackageResourceReference imageReference, 052 boolean removeWhitespaces) throws ResourceStreamNotFoundException, IOException 053 { 054 IResourceStream resourceStream = imageReference.getResource().getResourceStream(); 055 InputStream inputStream = resourceStream.getInputStream(); 056 try 057 { 058 byte[] bytes = IOUtils.toByteArray(inputStream); 059 String base64EncodedImage = Base64.getEncoder().encodeToString(bytes); 060 return "data:" + resourceStream.getContentType() + ";base64," + 061 (removeWhitespaces ? base64EncodedImage.replaceAll("\\s", "") : base64EncodedImage); 062 } 063 finally 064 { 065 IOUtils.closeQuietly(inputStream); 066 } 067 } 068}