In C#, how can I know the file type from a byte[]?

As mentioned, MIME magic is the only way to do this. Many platforms provide up-to-date and robust MIME magic files and code to do this efficiently. The only way to do this in .NET without any 3rd party code is to use FindMimeFromData from urlmon.dll. Here’s how: public static int MimeSampleSize = 256; public static … Read more

How to convert hex to a byte array?

Something like this: using System; public static class Parser { static void Main() { string hex = “0xBAC893CAB8B7FE03C927417A2A3F6A6” + “0BD30FF35E250011CB25507EBFCD5223B”; byte[] parsed = ParseHex(hex); // Just for confirmation… Console.WriteLine(BitConverter.ToString(parsed)); } public static byte[] ParseHex(string hex) { int offset = hex.StartsWith(“0x”) ? 2 : 0; if ((hex.Length % 2) != 0) { throw new ArgumentException(“Invalid length: … Read more

Rotate an YUV byte array on Android

The following method can rotate a YUV420 byte array by 90 degree. private byte[] rotateYUV420Degree90(byte[] data, int imageWidth, int imageHeight) { byte [] yuv = new byte[imageWidth*imageHeight*3/2]; // Rotate the Y luma int i = 0; for(int x = 0;x < imageWidth;x++) { for(int y = imageHeight-1;y >= 0;y–) { yuv[i] = data[y*imageWidth+x]; i++; } … Read more

Convert Access image OLE Object into raw image byte array in C#

The problem here is that the imbedded image was not a simple BMP or JPEG. It was a Microsoft Word Picture and the OLE header information was considerably larger than the 300 byte window of the original GetImageBytesFromOLEField() code. (That is, after scanning 300 bytes it just gave up with “Unable to determine header size…”.) … Read more

Put byte array to JSON and vice versa

Here is a good example of base64 encoding byte arrays. It gets more complicated when you throw unicode characters in the mix to send things like PDF documents. After encoding a byte array the encoded string can be used as a JSON property value. Apache commons offers good utilities: byte[] bytes = getByteArr(); String base64String … Read more

Java: object to byte[] and byte[] to object converter (for Tokyo Cabinet)

public static byte[] serialize(Object obj) throws IOException { ByteArrayOutputStream out = new ByteArrayOutputStream(); ObjectOutputStream os = new ObjectOutputStream(out); os.writeObject(obj); return out.toByteArray(); } public static Object deserialize(byte[] data) throws IOException, ClassNotFoundException { ByteArrayInputStream in = new ByteArrayInputStream(data); ObjectInputStream is = new ObjectInputStream(in); return is.readObject(); }