如何在java中将图像转换为字符串,反之亦然
如何在java中将图像转换为字符串,反之亦然。 我将file.jpg转换为字节数组,然后将字节数组转换为字符串,但当我将结果字符串重新转换为图像时,出现了错误 这是代码如何在java中将图像转换为字符串,反之亦然,java,Java,如何在java中将图像转换为字符串,反之亦然。 我将file.jpg转换为字节数组,然后将字节数组转换为字符串,但当我将结果字符串重新转换为图像时,出现了错误 这是代码 public void StringToFile( String s1, String filename ) { byte[] byte02 = s1.getBytes( ); //byte[] byte02 = s1.getBytes( StandardCharsets.UTF_
public void StringToFile( String s1, String filename ) {
byte[] byte02 = s1.getBytes( );
//byte[] byte02 = s1.getBytes( StandardCharsets.UTF_8 );
try {
System.out.println( "Data is corrupted when converting image "
+ "file to String and vice versa, this function is just a test" );
FileOutputStream output = new FileOutputStream( filename );
output.write( byte02 );
output.close();
ByteArrayInputStream bis = new ByteArrayInputStream( byte02 );
BufferedImage bImage2 = ImageIO.read( bis );
ImageIO.write( bImage2, "jpg", new File( filename ) );
}
catch ( Exception ex ) {
System.out.println( ex.getMessage() );
}
}
当您将二进制数据转换为常规字符串时,可能会出现问题 原因是将字节数组转换为字符串使用系统的字符编码将字节转换为字符。在此过程中,未映射字符的字节将丢失或修改 相反,我建议你使用
java.util.Base64.getEncoder().encodeToString(byte[])
将文件的字节转换为字符串值,然后
java.util.Base64.getDecoder().decode(String)
如有可能,避免将二进制数据(如图形文件)转换为字符串<代码>字符串意味着包含一系列Unicode字符,而不是任意数据。如果需要将二进制数据转换为可打印字符,请使用中给出的方法,即类似base 64的编码 在Android上,要将
位图
转换为字节[]
,可以使用位图压缩方法:
import android.graphics.Bitmap;
private byte[] getBytesFromImage (Bitmap image) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
BitmapFactory.decodeByteArrray(imageBytes, 0, imageBytes.length); // imageBytes is the byte[] array of the image that was returned by the getBytesFromImage method.
此方法返回一个byte[]数组,您可以使用该数组将图像存储在数据库中,例如,作为Blob值
要将字节[]转换为图像,请使用BitmapFactory.decodeByteArray
方法:
import android.graphics.Bitmap;
private byte[] getBytesFromImage (Bitmap image) {
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
image.compress(Bitmap.CompressFormat.PNG, 0, outputStream);
return outputStream.toByteArray();
}
BitmapFactory.decodeByteArrray(imageBytes, 0, imageBytes.length); // imageBytes is the byte[] array of the image that was returned by the getBytesFromImage method.
还请显示如何从file.jpg创建字符串的代码!有可能是在调用StringToFile
之前已经造成了损坏,很可能是在您从字节数组创建字符串的时候String
并不意味着包含任意二进制数据,因此如果您尝试这样做,就会有很多陷阱。通常,对于二进制数据使用字节数组是最好的做法。请提供完整的错误消息,并提供一个。