简体   繁体   中英

Can't figure out where these C# and Java code differ

I have some C# code that converts an image to base64 string. The code is :

MemoryStream ms = new MemoryStream();
Image img = Image.FromFile(filename);
img.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
string s = Convert.ToBase64String(ms.GetBuffer());

I am trying to implement it with JAVA. my java code is :

BufferedImage img = null;
img = ImageIO.read(new File(filename));
byte[] bytes = ((DataBufferByte)img.getData().getDataBuffer()).getData();
String js = Base64.encodeBase64String(bytes);

this two piece of code should return the same string for the same image file. But they are returning different strings. I am unable to figure out why. Can anyone shed some light on it?

this two piece of code should return the same string for the same image file

No, they really shouldn't.

The C# code is returning the base64 representation of a JPEG-encoded version of the image data - and potentially some 0s at the end, as you're using GetBuffer instead of ToArray . (You want ToArray here.)

The Java code is returning the base64 representation of the raw raster data, according to its SampleModel . I'd expect this to be significantly larger than the string returned by the C# code.

Even if both pieces of code encoded the image with the same format, that doesn't mean they'll come up with the exact same data - it will depend on the encoding.

Importantly, if you just want "the contents of the file in base64" then you don't need to go via an Image at all. For example, in C# you could use:

string base64 = Convert.ToBase64String(File.ReadAllBytes(filename));

The fact that it's an image is irrelevant in that respect - the file is just a collection of bytes, and you can base64-encode that without understanding the meaning of those bytes at all.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM