如何将Base64编码的图像写入文件?
我已使用 Base64 将图像编码为字符串。 首先,我读取文件,然后将其转换为字节数组,然后应用 Base64 编码将图像转换为字符串。
现在我的问题是如何解码它。
byte dearr[] = Base64.decodeBase64(crntImage);
File outF = new File("c:/decode/abc.bmp");
BufferedImage img02 = ImageIO.write(img02, "bmp", outF);
变量
crntImage
包含图像的字符串表示形式。
假设图像数据已经是您想要的格式,您根本不需要
ImageIO
- 您只需将数据写入文件即可:
// Note preferred way of declaring an array variable
byte[] data = Base64.decodeBase64(crntImage);
try (OutputStream stream = new FileOutputStream("c:/decode/abc.bmp")) {
stream.write(data);
}
(我假设您在这里使用 Java 7 - 如果没有,您需要编写手动 try/finally 语句来关闭流。)
如果图像数据不是您想要的格式,您需要提供更多详细信息。
Base64
APIbyte[] decodedImg = Base64.getDecoder()
.decode(encodedImg.getBytes(StandardCharsets.UTF_8));
Path destinationFile = Paths.get("/path/to/imageDir", "myImage.jpg");
Files.write(destinationFile, decodedImg);
如果您的编码图像以类似
data:image/png;base64,iVBORw0...
的内容开头,则必须删除该部分。请参阅这个答案,了解一种简单的方法。
无需使用 BufferedImage,因为您已经拥有字节数组中的图像文件
byte dearr[] = Base64.decodeBase64(crntImage);
FileOutputStream fos = new FileOutputStream(new File("c:/decode/abc.bmp"));
fos.write(dearr);
fos.close();
import java.util.Base64;
....只是明确表示此答案使用 java.util.Base64 包,而不使用任何第三方库。
String crntImage=<a valid base 64 string>
byte[] data = Base64.getDecoder().decode(crntImage);
try( OutputStream stream = new FileOutputStream("d:/temp/abc.pdf") )
{
stream.write(data);
}
catch (Exception e)
{
System.err.println("Couldn't write to file...");
}
使用 apache-commons 的其他选项:
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.io.FileUtils;
...
File file = new File( "path" );
byte[] bytes = Base64.decodeBase64( "base64" );
FileUtils.writeByteArrayToFile( file, bytes );
public class MensajeArchivoDto {
private String base64;
private String ruta;
private String nom_archivo;
private String ext_archivo;
}
-----------
@Override
public void descargarArchivo(MensajeArchivoDto msgArchivo) {
List<ErrorEntity> lstErrores = new ArrayList<ErrorEntity>();
try {
String rutaRaiz = "D:\\";
byte[] archivoByte = Base64.getDecoder().decode(msgArchivo.getBase64());
String rutaCompleta =rutaRaiz+ msgArchivo.getRuta();
crearDirectorio(rutaCompleta);
String nombreCompleto =rutaCompleta+"\\"+msgArchivo.getNom_archivo()+"."+msgArchivo.getExt_archivo();
OutputStream out = new FileOutputStream(nombreCompleto);
out.write(archivoByte);
out.close();
} catch (Exception e) {
lstErrores.add(new ErrorEntity("Exception", e.getMessage()));
}
}
private void crearDirectorio(String ruta) {
try {
File directorio = new File(ruta);
if (!directorio.exists()) {
if (directorio.mkdirs()) {
System.out.println("Directorio creado");
} else {
System.out.println("Error al crear directorio");
}
}
} catch (Exception e) {
lstErrores.add(new ErrorEntity("Exception", e.getMessage()));
}
}
试试这个:
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.URL;
import javax.imageio.ImageIO;
public class WriteImage
{
public static void main( String[] args )
{
BufferedImage image = null;
try {
URL url = new URL("URL_IMAGE");
image = ImageIO.read(url);
ImageIO.write(image, "jpg",new File("C:\\out.jpg"));
ImageIO.write(image, "gif",new File("C:\\out.gif"));
ImageIO.write(image, "png",new File("C:\\out.png"));
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("Done");
}
}