4

Converting a multi page tiff file to base64 string by using known conversion methods seems to contain just a single page of it.

I'm getting the multi page tiff file from local disk:

Image multiPageImage = Image.FromFile(fileName);

Converting it to base64 string:

base64string = ImageToBase64(multiPageImage, ImageFormat.Tiff);

public static string ImageToBase64(Image image, ImageFormat format)
{
    using (MemoryStream ms = new MemoryStream())
    {
        // Convert Image to byte[]
        image.Save(ms, format);
        byte[] imageBytes = ms.ToArray();

        // Convert byte[] to Base64 String
        string base64String = Convert.ToBase64String(imageBytes);

        image.Dispose();

        return base64String;
    }  
}

Then converting base64 to image back and saving it on the local disk to control the result:

public static Image ConvertBase64ToImage(string base64string)
{
    byte[] bytes = Convert.FromBase64String(base64string);

    Image image;

    using (MemoryStream ms = new MemoryStream(bytes))
    {
        image = Image.FromStream(ms);

        image.Save(@"C:\newTiff.tiff", ImageFormat.Tiff);
    }

    return image;
}

But result image has only single frame. That's why I'm asking if it is possible to have all frames in base64 string?

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
Orkun Bekar
  • 1,447
  • 1
  • 15
  • 36

1 Answers1

8

You are doing lot of unnecessary stuff just for reading a file and write it back to disk.

You can read all the content of file like this

var data = File.ReadAllBytes("image.tiff")

and then use Convert.ToBase64String(data) to convert it to a base 64 string.

var data = File.ReadAllBytes("image.tiff");
var result = Convert.ToBase64String(data);

then you can convert it back to it's byte representation and save it to disk.

var bytes = Convert.FromBase64String(result);
File.WriteAllBytes("image2.tiff", bytes);

File.ReadAllBytes()
Convert.ToBase64String()

Hamid Pourjam
  • 20,441
  • 9
  • 58
  • 74
  • The question _"How to base64-encode a file in C#"_ [has been answered before](http://stackoverflow.com/questions/475421/base64-encode-a-pdf-in-c). OP already is using code, which doesn't work. If they want help with that, they must show their code. – CodeCaster Jan 30 '15 at 09:10