Image sizing issue in bitmap - c#

I am using the below code to create bitmap. Image is getting created but not with the specified size. Is there any issue with code?
public class ProcessImage : IHttpHandler
{
public void ProcessRequest(HttpContext context)
{
var bmpOut = new Bitmap(100, 100);
var request = (HttpWebRequest)WebRequest.Create("http://media.zenfs.com/en_us/Sports/ap/201305061639599673916-p2.jpeg");
request.AllowWriteStreamBuffering = true;
var response = (HttpWebResponse) request.GetResponse();
var myStream = response.GetResponseStream();
var b = new Bitmap(myStream);
var g = Graphics.FromImage(bmpOut);
g.InterpolationMode = InterpolationMode.High;
g.DrawImage(b,0,0,50, 50);
context.Response.ContentType = "image/png";
var stream = new MemoryStream();
b.Save(stream, System.Drawing.Imaging.ImageFormat.Png);
b.Dispose();
stream.WriteTo(HttpContext.Current.Response.OutputStream);
//context.Response.Write("Hello World");
}

private Bitmap ResizeImage(Image image, int width, int height)
{
Bitmap result = new Bitmap(width, height);
result.SetResolution(image.HorizontalResolution, image.VerticalResolution);
using (Graphics graphics = Graphics.FromImage(result))
{
graphics.CompositingQuality = System.Drawing.Drawing2D.CompositingQuality.HighQuality;
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
graphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.HighQuality;
graphics.DrawImage(image, 0, 0, result.Width, result.Height);
}
return result;
}

Related

Writing on a bitmap not working for writing a frame with a forge

I need to output the video from a webcam to file with Aforge.
LocalWebCamsCollection = new FilterInfoCollection(FilterCategory.VideoInputDevice);
LocalWebCam = new VideoCaptureDevice(LocalWebCamsCollection[0].MonikerString);
LocalWebCam.NewFrame += LocalWebCam_NewFrame;
LocalWebCam.Start();
So when I get the frame I write it with:
private void LocalWebCam_NewFrame(object sender, AForge.Video.NewFrameEventArgs eventArgs)
{
try
{
System.Drawing.Image img = (System.Drawing.Bitmap)eventArgs.Frame.Clone();
MemoryStream ms = new MemoryStream();
img.Save(ms, ImageFormat.Bmp);
ms.Seek(0, SeekOrigin.Begin);
bi = new BitmapImage();
bi.BeginInit();
bi.StreamSource = ms;
bi.EndInit();
bi.Freeze();
Application.Current.Dispatcher.Invoke(() =>
{
var bmp2 = Helper.BitmapUtilities.BitmapImage2Bitmap(bi);
FileWriter.WriteVideoFrame(bmp2);
});
}
catch (Exception ex)
{
}
}
That works but then if I try to write the timestamp I get the error: "parameter not valid"
This is how I change it
System.Drawing.Bitmap bmpOut = null;
Application.Current.Dispatcher.Invoke(() =>
{
var visual = new DrawingVisual();
using (DrawingContext drawingContext = visual.RenderOpen())
{
drawingContext.DrawImage(bi, new Rect(0, 0, bi.Width, bi.Height));
drawingContext.DrawText(new FormattedText(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff"), CultureInfo.InvariantCulture, FlowDirection.LeftToRight, new Typeface("Segoe UI"), 32, Brushes.Red), new Point(0, 0));
}
var image = new DrawingImage(visual.Drawing);
#endregion
img_Webcam.Source = image;
using (MemoryStream ms = new MemoryStream())
{
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(ToBitmapSource(image)));
encoder.Save(ms);
using (System.Drawing.Bitmap bmp = new System.Drawing.Bitmap(ms))
{
bmpOut = new System.Drawing.Bitmap(bmp);
}
}
FileWriter.WriteVideoFrame(bmpOut);<---here the error
});
Perhaps I have not followed the best strategy so I am open to any other solution: what I need is just to write a timestamp on the bitmap (or bitmapimage) to be written on the file
Thanks for any help
Patrick
--- ADD ---
public static BitmapSource ToBitmapSource(DrawingImage source)
{
DrawingVisual drawingVisual = new DrawingVisual();
DrawingContext drawingContext = drawingVisual.RenderOpen();
drawingContext.DrawImage(source, new Rect(new Point(0, 0), new Size(source.Width, source.Height)));
drawingContext.Close();
RenderTargetBitmap bmp = new RenderTargetBitmap((int)source.Width, (int)source.Height, 96, 96, PixelFormats.Pbgra32);
bmp.Render(drawingVisual);
return bmp;
}

Cannot access a closed Stream? How to prevent it?

I am trying to run this code but I always get an error "cannot access a closed Stream"
private MemoryStream GetBitmap(Stream stream, int width, int height)
{
const int size = 150;
const int quality = 75;
using (var image = new Bitmap(System.Drawing.Image.FromStream(stream)))
{
//int width, height;
if (image.Width > image.Height)
{
width = size;
height = Convert.ToInt32(image.Height * size / (double)image.Width);
}
else
{
width = Convert.ToInt32(image.Width * size / (double)image.Height);
height = size;
}
var resized = new Bitmap(width, height);
using (var graphics = Graphics.FromImage(resized))
{
graphics.CompositingQuality = CompositingQuality.HighSpeed;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.DrawImage(image, 0, 0, width, height);
using (var output = new MemoryStream())
{
var qualityParamId = Encoder.Quality;
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(qualityParamId, quality);
var codec = ImageCodecInfo.GetImageDecoders()
.FirstOrDefault(codec => codec.FormatID == ImageFormat.Jpeg.Guid);
resized.Save(output, codec, encoderParameters);
return output;
}
}
}
}
Not sure how can I prevent Memorystream output from closing a Stream stream.
EDIT
After your suggestions here is the new code
public Stream GetBitmap(Stream stream)
{
using (var image = SystemDrawingImage.FromStream(stream))
{
var scaled = ScaledSize(image.Width, image.Height, ThumbnailSize);
var resized = new Bitmap(scaled.width, scaled.height);
using (var graphics = Graphics.FromImage(resized))
using (var attributes = new ImageAttributes())
{
attributes.SetWrapMode(WrapMode.TileFlipXY);
graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;
graphics.CompositingMode = CompositingMode.SourceCopy;
graphics.CompositingQuality = CompositingQuality.AssumeLinear;
graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
graphics.DrawImage(image, Rectangle.FromLTRB(0, 0, resized.Width, resized.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, attributes);
using (var encoderParams = new EncoderParameters(1))
using (var qualityParam = new EncoderParameter(Encoder.Quality, (long)Quality))
{
encoderParams.Param[0] = qualityParam;
var streamOutput = new MemoryStream();
resized.Save(streamOutput, systemDrawingJpegCodec, encoderParams);
return streamOutput;
}
}
}
}
Here is the controller action method
[HttpGet("{photoId}")]
public async Task<IActionResult> GetPhoto(intphotoId)
{
if (String.IsNullOrEmpty(photoid))
return NotFound();
var response = await _service.GetPhotoAsync(photoId);
Response.Headers.Add("Content-Disposition", new ContentDisposition()
{
FileName = "test.jpg",
Inline = true
}.ToString());
return File(response, "image/jpeg");
}
You're creating the MemoryStream in a using block. When the block goes out of scope the Dispose method is being called. Just remove the using so that it isn't closed:
var output = new MemoryStream())
var qualityParamId = Encoder.Quality;
var encoderParameters = new EncoderParameters(1);
encoderParameters.Param[0] = new EncoderParameter(qualityParamId, quality);
var codec = ImageCodecInfo.GetImageDecoders()
.FirstOrDefault(codec => codec.FormatID == ImageFormat.Jpeg.Guid);
resized.Save(output, codec, encoderParameters);
return output;
Also, if you're planning to have the caller read the stream then you'll probably want to reset the Position property so that anyone reading from it starts from the beginning:
output.Position = 0;
return output;

Generated Barcode Image not getting scanned through scanner in asp.net web application

I have generated dynamic barcode image in asp.net web application but its not getting scanned/reading through barcode scanner.
Below is the code where i have generated barcode image.kindly find it out.
Need Your Suggestion and help,awaiting your response.
string barCode = LblSerialNo.Text;
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
using (Bitmap bitMap = new Bitmap(barCode.Length * 11, 45))
{
using (Graphics graphics = Graphics.FromImage(bitMap))
{
Font oFont = new Font("IDAutomationHC39M", 8);
PointF point = new PointF(2f, 2f);
SolidBrush blackBrush = new SolidBrush(Color.Black);
SolidBrush whiteBrush = new SolidBrush(Color.White);
graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);
graphics.DrawString(barCode, oFont, blackBrush, point);
}
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
Convert.ToBase64String(byteImage);
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
plBarCode.Controls.Add(imgBarCode);
}

Barcode not generated in C# web forms?

I am trying for create a barcode in my web form.for that i download font IDAutomationHC39M and install in my system,then i run my wesite in localhost but barcode cannot be generated.This is my code
protected void Button1_Click1(object sender, EventArgs e)
{
string barCode = TextBox1.Text;
System.Web.UI.WebControls.Image imgBarCode = new System.Web.UI.WebControls.Image();
using (Bitmap bitMap = new Bitmap(barCode.Length * 40, 80))
{
using (Graphics graphics = Graphics.FromImage(bitMap))
{
Font oFont = new Font("IDAutomationHC39M", 16);
PointF point = new PointF(2f, 2f);
SolidBrush blackBrush = new SolidBrush(Color.Black);
SolidBrush whiteBrush = new SolidBrush(Color.White);
graphics.FillRectangle(whiteBrush, 0, 0, bitMap.Width, bitMap.Height);
graphics.DrawString("*" + barCode + "*", oFont, blackBrush, point);
}
using (MemoryStream ms = new MemoryStream())
{
bitMap.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] byteImage = ms.ToArray();
Convert.ToBase64String(byteImage);
imgBarCode.ImageUrl = "data:image/png;base64," + Convert.ToBase64String(byteImage);
}
plBarCode.Controls.Add(imgBarCode);
}
And the result is appear like that code

HttpHandler issue, Retrieving image

The following HttpHandler is to retrieve image from database. When I initially tested it it was working fine. but now the problem is that it still retieve image but does not display it in image control that is in Listview.
`public void ProcessRequest (HttpContext context)
{
string imageid = context.Request.QueryString["ImID"];
using (SqlConnection connection = ConnectionManager.GetConnection())
{
SqlCommand command = new SqlCommand("select Normal_Thumbs from User_Images where Id=" + imageid, connection);
SqlDataReader dr = command.ExecuteReader();
dr.Read();
if (dr[0] != DBNull.Value)
{
Stream str = new MemoryStream((Byte[])dr[0]);
Bitmap Photo = new Bitmap(str);
int Width = Photo.Width;
int Height = Photo.Height;
int imagesize = 200;
if (Photo.Width > Photo.Height)
{
Width = imagesize;
Height = Photo.Height * imagesize / Photo.Width;
}
else
{
Width = Photo.Width * imagesize / Photo.Height;
Height = imagesize;
}
Bitmap bmpOut = new Bitmap(150, 150);
Graphics g = Graphics.FromImage(bmpOut);
g.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
g.FillRectangle(Brushes.White, 0, 0, Width, Height);
g.DrawImage(Photo, 0, 0, Width, Height);
MemoryStream ms = new MemoryStream();
bmpOut.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
byte[] bmpBytes = ms.GetBuffer();
bmpOut.Dispose();
ms.Close();
context.Response.Write(bmpBytes);
context.Response.End();
}
}
}
The Handler Retrieves the image but the listview does not display it.
Try this approach, setting content type to the response.
...
context.Response.Clear();
context.Response.ContentType = System.Drawing.Imaging.ImageFormat.Png.ToString();
context.Response.OutputStream.Write(bmpBytes, 0, bmpBytes.Length);
context.Response.End();
...
Regards.

Categories

Resources