I'm developing a Windows Forms application where one of the things i need to do is, extract the image from .img file. I'm being able to read the normal jpg and png files, but not .img file.
I could not find much information on internet regarding this. I did find some code on msdn and i tried to get it to work. Below is the code and exception that is being thrown.
FileInfo file = new FileInfo(FilePath.Text);
FileStream f1 = new FileStream(FilePath.Text, FileMode.Open,
FileAccess.Read, FileShare.Read);
byte[] BytesOfPic = new byte[Convert.ToInt32(file.Length)];
f1.Read(BytesOfPic, 0, Convert.ToInt32(file.Length));
MemoryStream mStream = new MemoryStream();
mStream.Write(BytesOfPic, 0, Convert.ToInt32(BytesOfPic.Length));
Bitmap bm = new Bitmap(mStream, false);
mStream.Dispose();
// ImageBox is name of a PictureBox
ImageBox.image = bm; // this line is throwing the error
Exception caught
System.ArgumentException: Parameter is not valid.
at System.Drawing.Bitmap..ctor(Stream stream, Boolean useIcm)
at A02_Stegnography.Form1.ReadImgFile() in C:\Users\tiwar\Desktop\A02-Stegnography\A02-Stegnography\Form1.cs:line 65
I'm sorry if this is a stupid question. I hope i have provided enough information but if i haven't please let me know.
FileInfo file = new FileInfo(FilePath.Text);
FileStream f1 = new FileStream(FilePath.Text, FileMode.Open,
FileAccess.Read, FileShare.Read);
byte[] BytesOfPic = new byte[Convert.ToInt32(file.Length)];
f1.Read(BytesOfPic, 0, Convert.ToInt32(file.Length));
using (MemoryStream mStream = new MemoryStream())
{
mStream.Write(BytesOfPic, 0, BytesOfPic.Length);
mStream.Seek(0, SeekOrigin.Begin);
Bitmap bm = new Bitmap(mStream);
// ImageBox is name of a PictureBox
ImageBox.image = bm;
}
You can try my solution for problem
Related
I'm trying to take a screenshot of the screen in C# Windows Forms. Code (from https://www.c-sharpcorner.com/UploadFile/2d2d83/how-to-capture-a-screen-using-C-Sharp/):
Bitmap captureBitmap = new Bitmap(1600, 900, PixelFormat.Format32bppArgb);
Rectangle captureRectangle = Screen.AllScreens[0].Bounds;
Graphics captureGraphics = Graphics.FromImage(captureBitmap);
captureGraphics.CopyFromScreen(captureRectangle.Left, captureRectangle.Top, 0, 0, captureRectangle.Size);
captureBitmap.Save(#"C:\Screenshot.jpg", ImageFormat.Jpeg);
It throws this error: A generic error occured in GDI+ (in captureBitmap.Save).
What can I do? I tried using captureBitmap.Dispose() but it still doesn't work.
You can replace your last line
captureBitmap.Save(#"C:\Screenshot.jpg", ImageFormat.Jpeg);
to
string outputFileName = #"C:\Screenshot.jpg";
using (MemoryStream memory = new MemoryStream())
{
using (FileStream fs = new FileStream(outputFileName, FileMode.Create, FileAccess.ReadWrite))
{
captureBitmap.Save(memory, ImageFormat.Jpeg);
byte[] bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
}
}
Reason and LINK for further read
I need to convert a byte[] to an Image, but I cannot make it work in C#. If I save the bytearray to a file like this:
using (System.IO.FileStream fs = System.IO.File.Create("test.jpg"))
{
fs.Write(bytearray, 0, (int)lenght);
fs.Close();
}
And test.jpg shows properly. But when I try to make Image from the bytearray like this:
MemoryStream ms = new MemoryStream(bytearray);
pictureBox1.Image = Image.FromStream(ms);
It shows only black box.
I guess one problem is since you are creating test.jpg, it doesn't have any data and so the bytearray is empty.
Do something like :-
byte[] fileData = null;
using (var fs = new FileStream("C:\\1\\roses.jpg", FileMode.Open, FileAccess.Read))
{
var totalLength = (int)fs.Length;
using (var binaryReader = new BinaryReader(fs))
{
fileData = new byte[totalLength];
fs.Read(fileData, 0, totalLength);
fs.Close();
}
MemoryStream ms = new MemoryStream(fileData);
pictureBox1.Image = Image.FromStream(ms);
}
Okay, all was my bad. The code is correct, but the reason why it was showing only black screen was, becuase the picture was so big and it was black in the corners. And the pictureBox was not resizing it or anything so it showed its top right corner only.
With the way below i am able to read.
But there is no dispose method so i am not able to delete the file later.
So the below method is getting failed.
I could not come up with a proper solution.
Bitmap class is not recognized in C# 4.5 WPF application.
thank you
DirectoryInfo dInfo = new DirectoryInfo(#"C:\pokemon_files\images\");
FileInfo[] subFiles = dInfo.GetFiles();
BitmapImage myImg;
foreach (var vrImage in subFiles)
{
string srFilePath = vrImage.FullName;
System.Uri myUri = new Uri(srFilePath);
myImg = new BitmapImage(myUri);
if (myImg.Width < 50)
{
File.Delete(srFilePath);
continue;
}
}
I assume the error you get is caused by trying to delete the file which is currently in use
by the bitmap (I don't remember the exception name).
There is a solution to that, that is: making a byte stream.
byte[] imageData;
using(var fileStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
using(var binaryReader = new BinaryReader(fileStream))
{
imageData = binaryReader.ReadBytes((int)fileStream.Length);
}
var bitmap = new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = new MemoryStream(imageData);
bitmap.EndInit();
//Now you can check the width & height, the file stream should be closed so you can
//delete the file.
[EDIT]
If you don't want to read the bytes by BinaryReader, there's always this solution if you want to read all bytes from the file.
I have some set of TIFF files (8-bit palette). I need to change the bit depth into 32 bit.
I tried the code below, but getting an error, that the parameter is not correct... Could you help me to fix it? Or maybe some1 is able to suggest some different solution for my problem.
public static class TiffConverter
{
public static void Convert8To32Bit(string fileName)
{
BitmapSource bitmapSource;
using (Stream imageStreamSource = new FileStream(fileName, FileMode.Open, FileAccess.Read, FileShare.Read))
{
TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
bitmapSource = decoder.Frames[0];
}
using (FileStream stream = new FileStream(fileName, FileMode.OpenOrCreate))
{
ImageCodecInfo tiffCodec = ImageCodecInfo.GetImageEncoders().FirstOrDefault(codec => codec.FormatID.Equals(ImageFormat.Tiff.Guid));
if (tiffCodec != null)
{
Image image = BitmapFromSource(bitmapSource);
EncoderParameters parameters = new EncoderParameters();
parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 32);
image.Save(stream, tiffCodec, parameters);
}
}
}
private static Bitmap BitmapFromSource(BitmapSource bitmapSource)
{
Bitmap bitmap;
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder enc = new BmpBitmapEncoder();
enc.Frames.Add(BitmapFrame.Create(bitmapSource));
enc.Save(outStream);
bitmap = new Bitmap(outStream);
}
return bitmap;
}
}
Thanks in advance!
[edit]
I noticed that the error appears in this line:
image.Save(stream, tiffCodec, parameters);
ArgumentException occured: Parameter is not valid.
If the error you're getting is on the line:
parameters.Param[0] = new EncoderParameter(Encoder.ColorDepth, 32);
then the problem is that the compiler cannot know if you're referring System.Text.Encoder or System.Drawing.Imaging.Encoder...
Your code should look like this to to avoid any ambiguity:
parameters.Param[0] = new EncoderParameter(System.Drawing.Imaging.Encoder.ColorDepth, 32);
Edit:
This is an alternative (and tested :)) way of doing the same thing:
Image inputImg = Image.FromFile("input.tif");
var outputImg = new Bitmap(inputImg.Width, inputImg.Height, System.Drawing.Imaging.PixelFormat.Format32bppArgb);
using (var gr = Graphics.FromImage(outputImg))
gr.DrawImage(inputImg, new Rectangle(0, 0, inputImg.Width, inputImg.Height));
outputImg.Save("output.tif", ImageFormat.Tiff);
I'm trying to save a bitmap to my isolated storage as a png file. I found a library on Codeplex called ImageTools which people have been recommending but when i try it and attempt to open the file it says that its corrupt. Any know what i am doing wrong?
private static void SaveImageToIsolatedStorageAsPng(BitmapImage bitmap, string fileName)
{
//convert to memory stream
MemoryStream memoryStream = new MemoryStream();
WriteableBitmap writableBitmap = new WriteableBitmap(bitmap);
writableBitmap.SaveJpeg(memoryStream, bitmap.PixelWidth, bitmap.PixelHeight, 0, 100);
//encode memory stream as PNG
ExtendedImage image = new ExtendedImage();
image.SetSource(memoryStream);
PngEncoder encoder = new PngEncoder();
//Save to IsolatedStorage
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
using (var writeStream = new IsolatedStorageFileStream(fileName, FileMode.Create, store))
{
encoder.Encode(image, writeStream);
}
}
You're attempting to convert the JPEG memory stream into PNG. That will make it corrupt - you should save the Bitmap directly to PNG.
I haven't tried this particular task with the imagetools library, but if you see John Papa's blog, it looks like you need to call the ToImage extension method on your WriteableBitmap which is provided as part of ImageTools. Then you can use the encoder to take this image and write out to your open stream.
var img = bitmap.ToImage();
var encoder = new PngEncoder();
using (var stream = new IsolatedStorageFileStream(fileName, FileMode.Create, store))
{
encoder.Encode(img, stream);
stream.Close();
}