Home > other >  Saving text content from image file as image file in C#
Saving text content from image file as image file in C#

Time:03-30

I am trying to save a file contents as an image file and stuck. In the code below, original.png is a valid PNG file.

string fileContent = File.ReadAllText(@"C:\temp\original.png");

What I've been trying is simply to save the fileContent as C:\temp\resaved.png.

Attempted various ways, including using Image object, writing to FileStream and save, etc. but none worked.Any tips would be appreciated!

The original file actually comes from network, but the content is the same as loading with File.ReadAllText.

CodePudding user response:

Using this code below I was able to accomplish creating a new image from a different one obtained on a network connection:

using System;
using System.IO;
using System.Net;
using System.Threading.Tasks;

namespace test
{
    class Program
    {
        static void Main(string[] args)
        {
            var x = Task.Run(() => download());
            x.Wait();
            byte[] fileContent = File.ReadAllBytes(@"c:\temp\image35.png");
            Console.WriteLine(fileContent);
            File.WriteAllBytes(@"c:\temp\image36.png", fileContent);
        }
        static async Task download()
        {
            using (WebClient client = new WebClient())
            {
                string url = "https://www.pngitem.com/pimgs/m/477-4772195_monster-monstersinc-mike-wazowski-mikewazowski-mike-wazowski-meme.png";
                client.DownloadFile(new Uri(url), @"c:\temp\image35.png");
            }
        }
    }
}

I can't be sure of the exact purpose of this as you can duplicate the image using DownloadFile if it is on a network, but this code obtains the original image and then duplicates it to the indicated file name. Task.Run() was used to ensure we are synchronized and the file is fully obtained before attempting to duplicate it.

We cannot use ReadAllText so easily because the encoding of a string and the encoding of the image will be different.

CodePudding user response:

Based on the comments in the post, it looks like it's impossible (or very difficult) to save a string as PNG once it's loaded with File.ReadAllText(@"C:\temp\original.png") (or ReadAsString, which I was doing in the real scenario). I should have used ReadAsByteArray or ReadAsStream against HttpResponseMessage.Content.Thanks @CaiusJard.

  • Related