1. I have some picture files on hand. I want to convert them into Image objects in c, and then use them.
public static System.Drawing.Image FromFile (string filename);
For example, create a winform project and set the background image of the form.
public partial class Form1 : Form { public Form1() { InitializeComponent(); Image image = Image.FromFile("Image.png"); this.BackgroundImage = image; } }
Operation effect:
2. Picture storage
1. The image object is saved as a byte array, and then stored in a file or database.
using (var memoryStream = new MemoryStream()) { var image = Image.FromFile("Image.png"); image.Save(memoryStream, ImageFormat.Png); var byteArr = memoryStream.ToArray(); }
2. Data read from files or databases can also be converted into Image objects.
var image1 = new ImageConverter().ConvertFrom(byteArr); this.BackgroundImage = (Image)image1;
Directly reading binary data stored in Image file can also be converted into Image object.
var originByte = File.ReadAllBytes("Image.png"); var image1 = new ImageConverter().ConvertFrom(originByte); this.BackgroundImage = (Image)image1;
Compare the binary data of the two, there are still differences. The Image object has a larger amount of data. But both kinds of data can be correctly parsed by ImageConverter.
private void button1_Click(object sender, EventArgs e) { using (var memoryStream = new MemoryStream()) { var image = Image.FromFile("Image.png"); image.Save(memoryStream, ImageFormat.Png); var byteArr = memoryStream.ToArray(); var originByte = File.ReadAllBytes("Image.png"); WriteData("imageObj.txt", byteArr); WriteData("originFile.txt", originByte); } } private static void WriteData(string filename, byte[] target) { var list = new List<string>(); for (var i = 0; i < target.Length; i++) { list.Add($"{i}-->{target[i]}"); } File.AppendAllLines(filename, list); }
I changed a very small picture for comparison. You can refer to the comparison fragment, which is different after the 36th byte.