There are many png and gif files in the package. How to change their extension to jpg using c # tools and methods?
1 answer
string dir = @"C:\temp"; foreach(string fileName in System.IO.Directory.GetFiles(dir, "*.png")) { System.IO.File.Move(fileName, System.IO.Path.ChangeExtension(fileName, ".jpg")); } Wait, do you and the contents of the files need to be rewritten to jpeg?
string dir = @"C:\temp"; foreach(string fileName in System.IO.Directory.GetFiles(dir, "*.png")) { using (System.Drawing.Image img = System.Drawing.Image.FromFile(fileName)) { img.Save(System.IO.Path.ChangeExtension(fileName, ".jpg"), System.Drawing.Imaging.ImageFormat.Jpeg); } System.IO.File.Delete(fileName); } UPDATE
Extension (extension) in the file name is a convention that serves, first of all, for convenience - it is immediately clear what type of data the file contains. In this sense, all image files could have the extension ".picture". “But we know” that there are many types of pictures (even raster, not to mention vector ones). The internal structure of files with pictures of different formats is different. And only a program that knows about these formats and who can read and interpret them can show these pictures correctly. And if we drop such a program a file with a picture in a format that is unknown to it, the program will not be able to correctly display this file - no matter how we call this file.
If you look at files with pictures of different formats in (for example) Notepad, you will notice that the first few bytes contain an indication of the format. Based on this format marker, the program with which you open your pictures, knows that they have "inside", as Professor Vygegallo would say. And this is precisely the factor that determines how information about the image will be read and displayed.
The second variant of the code, for each file with the extension ".png", loads the image into the Image object and honestly saves this image in JPEG format into a new file with the extension ".jpg".
- How to understand the content? I manually renamed a few pieces - everything works fine. Pictures are alive, or are you talking about? - Andrei
- "Pictures are alive" - ​​what's this? There was such a magazine - "Merry Pictures". Are you satisfied with the code? - Igor
- Changing extensions did not affect file performance. The size has not changed too - Andrew
- Probably satisfied. I will try now - Andrew
- oneFrom the fact that we rename the file, what is inside the file does not turn from PNG to JPEG. - Igor