How to save image as stream? - c#

I am trying to create a screenshot and send it from C# to PHP where I store it.
I create a screenshot like this:
Bitmap screenshot = TakeScreenshot();
Now I try to save it as a stream:
Stream myStream;
screenshot.Save(myStream, System.Drawing.Imaging.ImageFormat.Gif);
However, I get Use of unassigned local variable 'myStream'.
What am I doing wrong?
Functions:
private Bitmap TakeScreenshot()
{
//Create a new bitmap.
var bmpScreenshot = new Bitmap(Screen.PrimaryScreen.Bounds.Width,
Screen.PrimaryScreen.Bounds.Height,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
// Create a graphics object from the bitmap.
using (var gfxScreenshot = Graphics.FromImage(bmpScreenshot))
{
// Take the screenshot from the upper left corner to the right bottom corner.
gfxScreenshot.CopyFromScreen(Screen.PrimaryScreen.Bounds.X,
Screen.PrimaryScreen.Bounds.Y,
0,
0,
Screen.PrimaryScreen.Bounds.Size,
CopyPixelOperation.SourceCopy);
}
return bmpScreenshot;
}

You have to initialize your stream before using it.
using (MemoryStream myStream = new MemoryStream()) {
screenshot.Save(myStream, System.Drawing.Imaging.ImageFormat.Gif);
}

By Stream you mean FileStream, MemoryStream, what? Whatever the case, just initialize the variable to be the proper kind of stream you need.
For example:
using(var myStream = new MemoryStream())
{....}

Related

Capture screenshot of control with different DPI

I can capture screenshot of control for normal 100% DPI. But when the DPI changed to 125% then the screenshot is not proper. Please suggest approach so that the screenshot can be captured with any DPI. Following is the code
// Get absolute location on screen of upper left corner of button
System.Windows.Point locationFromScreen = this.sv.PointToScreen(new System.Windows.Point(0, 0));
// Transform screen point to WPF device independent point
PresentationSource source = PresentationSource.FromVisual(this);
System.Windows.Point targetPoints = source.CompositionTarget.TransformFromDevice.Transform(locationFromScreen);
var bmpScreenshot = new Bitmap((int)sv.ActualWidth,
(int)sv.ActualHeight,
System.Drawing.Imaging.PixelFormat.Format32bppArgb);
// Create a graphics object from the bitmap.
var gfxScreenshot = Graphics.FromImage(bmpScreenshot);
gfxScreenshot.CopyFromScreen((int)targetPoints.X,
(int)targetPoints.Y,
0,
0,
new System.Drawing.Size((int)sv.ActualWidth, (int)sv.ActualHeight),
CopyPixelOperation.SourceCopy);
byte[] data;
using (var stream = new System.IO.MemoryStream())
{
bmpScreenshot.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
data = stream.ToArray();
}
var result = Convert.ToBase64String(data);
winObj = new Window1();
MemoryStream ms = new MemoryStream();
((System.Drawing.Bitmap)bmpScreenshot).Save(ms, System.Drawing.Imaging.ImageFormat.Bmp);
BitmapImage image = new BitmapImage();
image.BeginInit();
ms.Seek(0, SeekOrigin.Begin);
image.StreamSource = ms;
image.EndInit();
winObj.imageViewer.Source = image;
winObj.ShowDialog();
bmpScreenshot.Dispose();

How can i convert Bitmap to memory stream?

I have a code in form1 constructor:
ConvertedBmp = ConvertTo24(newest.FullName);
The function ConvertTo24 is:
private static Bitmap ConvertTo24(string inputFileName)
{
sw = Stopwatch.StartNew();
Bitmap bmpIn = (Bitmap)Bitmap.FromFile(inputFileName);
Bitmap converted = new Bitmap(bmpIn.Width, bmpIn.Height, PixelFormat.Format24bppRgb);
using (Graphics g = Graphics.FromImage(converted))
{
g.PageUnit = GraphicsUnit.Pixel;
g.DrawImageUnscaled(bmpIn, 0, 0);
}
sw.Stop();
return converted;
}
The problem is how can i use the ConvertedBmp in this line:
backTexture = TextureLoader.FromFile(D3Ddev, #"D:\test.bmp");
TextureLoader have some properties and two of them are: Fromfile and it's getting device and string or FromStream and it's getting device and Stream.
I have the device object already but how can i use the ConvertedBmp(Bitmap type) with the TextureLoader ?
Bitmap class has a method called Save() which accepts a Stream (for example a MemoryStream object) and an ImageFormat, use that. After saved the Bitmap into a MemoryStream you can use that with TextureLoader.
Image.Save Method (Stream, ImageFormat)
I get below code from here:
http://www.java2s.com/example/csharp/system.drawing/bitmap-to-memory-stream.html
public static MemoryStream ToMemoryStream(this Bitmap b)
{
MemoryStream ms = new MemoryStream();
b.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
return ms;
}
Work for my need

convert binary to bitmap using memory stream

Hi I wanna convert binary array to bitmap and show image in a picturebox. I wrote the following code but I got exception that says that the parameter is not valid .
public static Bitmap ByteToImage(byte[] blob)
{
MemoryStream mStream = new MemoryStream();
byte[] pData = blob;
mStream.Write(pData, 0, Convert.ToInt32(pData.Length));
Bitmap bm = new Bitmap(mStream);
mStream.Dispose();
return bm;
}
It really depends on what is in blob. Is it a valid bitmap format (like PNG, BMP, GIF, etc?). If it is raw byte information about the pixels in the bitmap, you can not do it like that.
It may help to rewind the stream to the beginning using mStream.Seek(0, SeekOrigin.Begin) before the line Bitmap bm = new Bitmap(mStream);.
public static Bitmap ByteToImage(byte[] blob)
{
using (MemoryStream mStream = new MemoryStream())
{
mStream.Write(blob, 0, blob.Length);
mStream.Seek(0, SeekOrigin.Begin);
Bitmap bm = new Bitmap(mStream);
return bm;
}
}
Don't dispose of the MemoryStream. It now belongs to the image object and will be disposed when you dispose the image.
Also consider doing it like this
var ms = new MemoryStream(blob);
var img = Image.FromStream(ms);
.....
img.Dispose(); //once you are done with the image.
System.IO.MemoryStream mStrm = new System.IO.MemoryStream(your byte array);
Image im = Image.FromStream(mStrm);
im.Save("image.bmp");
Try this. If you still get any error or exception; please post your bytes which you are trying to convert to image. There should be problem in your image stream....

How to crop a tiff image in asp.net

I was looking for a routine by which I can crop tiff image and I got it but it gives many error. Here is the routine:
Bitmap comments = null;
string input = "somepath";
// Open a Stream and decode a TIFF image
using (Stream imageStreamSource = new FileStream(input, FileMode.Open, FileAccess.Read, FileShare.Read))
{
TiffBitmapDecoder decoder = new TiffBitmapDecoder(imageStreamSource, BitmapCreateOptions.PreservePixelFormat, BitmapCacheOption.Default);
BitmapSource bitmapSource = decoder.Frames[0];
using (Bitmap b = BitmapFromSource(bitmapSource))
{
Rectangle cropRect = new Rectangle(169, 1092, 567, 200);
comments = new Bitmap(cropRect.Width, cropRect.Height);
//first cropping
using (Graphics g = Graphics.FromImage(comments))
{
g.DrawImage(b, new Rectangle(0, 0, comments.Width, comments.Height),
cropRect,
GraphicsUnit.Pixel);
}
}
}
When I try to compile it, I get an error. I tried adding references to many assemblies searching google but couldn't resolve it. I got this code from this url:
http://snipplr.com/view/63053/
I am looking for advice.
TiffBitmapDecoder class is from Presentation.Core in another words it is from WPF.
BitmapFromSource isn't method of any .net framework class. You can convert BitmapSource to Bitmap using this code.
private Bitmap BitmapFromSource(BitmapSource bitmapsource)
{
Bitmap bitmap;
using (MemoryStream outStream = new MemoryStream())
{
BitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bitmapsource));
encoder.Save(outStream);
bitmap = new Bitmap(outStream);
}
return bitmap;
}

C# Image outofboundmemory exception

I have tried to convert binary data to Image. here is my code:
Byte[] bytes = (byte[])(reader["Avatar"]);
fs1.Write(bytes, 0, bytes.Length);
pictureBox1.Image = Image.FromFile("image.jpg");
pictureBox1.SizeMode = PictureBoxSizeMode.StretchImage;
pictureBox1.Refresh();
but the wrong is out of bound memory exception in line : "pictureBox1.Image = Image.FromFile("image.jpg");"
I do not know why this happen, please help me
Try with this method:
public Image ImageFromBytes(byte[] bytes)
{
using(var ms = new MemoryStream(bytes))
{
return Image.FromStream(ms);
}
}
If fs1 is a stream you probably should close it before you access that file in the next line.
Note that you can also create the image in memory and avoid the file system completely.
You mast Close and Dispose your stream:
fs1.Write(bytes, 0, bytes.Length);
//Make sure you closed your stream
fs1.Close();
// You should call Dispose too.
fs1.Dispose();
pictureBox1.Image = Image.FromFile("image.jpg");
or enclose your writing file procces in using block:
using (Stream fs1 ...)
{
...
fs1.Write(bytes, 0, bytes.Length);
}

Categories