I am trying to use the ImageConverter class in my ASP.NET Core project to convert an Image to a byte[], but I can't seem to find the class.
I have installed the System.Drawing.Common package, but still can't find it.
I am using .NET Core 3.1.
If on .NET Core 3.1, ImageConverter requires the System.Windows.Extensions package:
https://learn.microsoft.com/en-us/dotnet/api/system.drawing.imageconverter?view=netcore-3.1
In .NET 5 it is included in System.Drawing.Common:
https://learn.microsoft.com/en-us/dotnet/api/system.drawing.imageconverter?view=net-5.0
You can convert image to byte easily.
protected virtual byte[] LoadPictureFromFile(string filePath)
{
if (!File.Exists(filePath))
return new byte[0];
return File.ReadAllBytes(filePath);
}
Extra help..
public byte[] ResizeImage(byte[] pictureBinary,int newWidth, int newHeight)
{
byte[] pictureBinaryResized;
using (var stream = new MemoryStream(pictureBinary))
{
Bitmap b = null;
try
{
//try-catch to ensure that picture binary is really OK. Otherwise, we can get "Parameter is not valid" exception if binary is corrupted for some reasons
b = new Bitmap(stream);
}
catch (ArgumentException exc)
{
// log error
}
if (b == null)
{
//bitmap could not be loaded for some reasons
return new byte[0];
}
using (var destStream = new MemoryStream())
{
ImageBuilder.Current.Build(b, destStream, new ResizeSettings
{
Width = newWidth,
Height = newHeight,
Scale = ScaleMode.Both,
Quality = _mediaSettings.DefaultImageQuality
});
pictureBinaryResized = destStream.ToArray();
b.Dispose();
}
}
return pictureBinaryResized;
}
Instead of ImageConverter, you can trying to look at this for speed up:
Save bitmap to stream:
bitmap.save(stream);
Or open image file:
FileStream stream = new FileStream(imageFilePath, FileMode.Open, FileAccess.Read);
Then simply use Stream2Bytes:
byte[] OO7b = Stream2Bytes(stream);
And this is the Stream2Bytes method:
public byte[] Stream2Bytes(Stream stream, int chunkSize = 1024)
{
if (stream == null)
{
throw new System.ArgumentException("Parameter cannot be null", "stream");
}
if (chunkSize < 1)
{
throw new System.ArgumentException("Parameter must be greater than zero", "chunkSize");
}
if (chunkSize > 1024 * 64)
{
throw new System.ArgumentException(String.Format("Parameter must be less or equal {0}", 1024 * 64), "chunkSize");
}
List<byte> buffers = new List<byte>();
using (BinaryReader br = new BinaryReader(stream))
{
byte[] chunk = br.ReadBytes(chunkSize);
while (chunk.Length > 0)
{
buffers.AddRange(chunk);
chunk = br.ReadBytes(chunkSize);
}
}
return buffers.ToArray();
}
Related
i have problem with PushStreamContent in asp.net core.
It display video on the website but my problem is that it will buffer whole file and then play it when my goal is to buffer small part of it and play on the website. Code i have:
My endpoint for playing video in browser
public IActionResult Play(string file)
{
var fileName = "C:\\repo\\trailer1.mp4";
var video = new VideoStream(fileName);
var response = new PushStreamContent(video.WriteToStream, new MediaTypeHeaderValue("video/mp4"))
{
};
var objectResult = new ObjectResult(response);
objectResult.ContentTypes.Add(new Microsoft.Net.Http.Headers.MediaTypeHeaderValue("video/mp4"));
return objectResult;
}
Ive got VideoStreamClass to help with displaying video
public class VideoStream
{
private readonly string _filename;
public VideoStream(string filename)
{
_filename = #"C:\\repo\\trailer1.mp4";
}
public async Task WriteToStream(Stream outputStream, HttpContent content, TransportContext context)
{
try
{
var buffer = new byte[65536];
using (var video = File.Open(_filename, FileMode.Open, FileAccess.Read))
{
var length = (int)video.Length;
var bytesRead = 1;
while (length > 0 && bytesRead > 0)
{
bytesRead = video.Read(buffer, 0, Math.Min(length, buffer.Length));
await outputStream.WriteAsync(buffer, 0, bytesRead);
await outputStream.FlushAsync();
length -= bytesRead;
}
}
}
catch (Exception)
{ return; }
finally
{
outputStream.Dispose();
}
}
}
And here is my VideoOutputFormatter added to bootstraper
public class VideoOutputFormatter : IOutputFormatter
{
public bool CanWriteResult(OutputFormatterCanWriteContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
if (context.Object is PushStreamContent)
return true;
return false;
}
public async Task WriteAsync(OutputFormatterWriteContext context)
{
if (context == null)
throw new ArgumentNullException(nameof(context));
using (var stream = ((PushStreamContent)context.Object))
{
var response = context.HttpContext.Response;
if (context.ContentType != null)
{
response.ContentType = context.ContentType.ToString();
}
await stream.CopyToAsync(response.Body);
}
}
}
I've tried to add atributes to controller "UseBufferedOutputStream" and "UseBufferedInputStream" setted to false but this still dosent work for me
ObjectResult is intended for holding an in-memory object as a response. If you want to return an existing file, then PhysicalFileResult is probably your best bet.
If you're interested in PushStreamContent, I believe the one you're using is for HttpClient, not ASP.NET. If you want a PushStreamContent equivalent, I have a FileCallbackResult that would work once it's updated for the latest .NET Core.
i have one use case, to convert byte array to image.How to do it. I have done some RND but getting error from below code.
public static bool IsValidImage(byte[] bytes)
{
try
{
using (MemoryStream ms = new MemoryStream(bytes))
{
Image image = Image.FromStream(ms);
}
}
catch (ArgumentException ex)
{
return false;
}
return true;
}
Please Suggest me
using wcf/wcf web services to upload a images give me with example?
In my project i want to upload image by using WCF
Basically you should use WCF streaming.
[ServiceContract]
public interface ITransferService
{
[OperationContract]
void UploadFile(RemoteFileInfo request);
}
public void UploadFile(RemoteFileInfo request)
{
FileStream targetStream = null;
Stream sourceStream = request.FileByteStream;
string uploadFolder = #"C:\\upload\\";
string filePath = Path.Combine(uploadFolder, request.FileName);
using (targetStream = new FileStream(filePath, FileMode.Create,
FileAccess.Write, FileShare.None))
{
//read from the input stream in 65000 byte chunks
const int bufferLen = 65000;
byte[] buffer = new byte[bufferLen];
int count = 0;
while ((count = sourceStream.Read(buffer, 0, bufferLen)) > 0)
{
// save to output stream
targetStream.Write(buffer, 0, count);
}
targetStream.Close();
sourceStream.Close();
}
}
The easiest way is to convert the image to a byte array before sending it, and then converting it back to an image on the destination site.
Here are two methods for doing just that:
public byte[] ImageToByteArray( Image image)
{
var ms = new MemoryStream();
image.Save(ms, ImageFormat.Png);
return ms.ToArray();
}
public static Image ByteArrayToImage(byte[] byteArray)
{
var ms = new MemoryStream(byteArray);
return Image.FromStream(ms);
}
That means your web service can have a method something like this:
public void UploadImage( byte[] imageData )
{
var image = ByteArrayToImage( imageData );
//save image to disk here, or do whatever you like with it
}
How to read the .mp3 audio files ?
I wrote the following code.
public static byte[] ReadFully(Stream stream)
{
byte[] buffer = new byte[32768];
using (MemoryStream ms = new MemoryStream())
{
while (true)
{
int read = stream.Read(buffer, 0, buffer.Length);
if (read <= 0)
return ms.ToArray();
ms.Write(buffer, 0, read);
}
}
It accepts .3gp,.caf foramat streams .why it's not taking .mp3 files?
}
I used the below code to download a mp3 file from my REST WCF Service:
[WebGet]
public Stream GetMp3()
{
byte[] buffer;
WebOperationContext.Current.OutgoingResponse.ContentType = "audio/mp3";
using (FileStream ms = new FileStream(#"C:\Sample.mp3", FileMode.Open))
{
int length = (int)ms.Length;
WebOperationContext.Current.OutgoingResponse.ContentLength = length;
buffer = new byte[length];
int sum = 0;
int count;
while ((count = ms.Read(buffer, sum, length - sum)) > 0)
{
sum += count;
}
ms.Close();
}
return new MemoryStream(buffer);
}
UPDATE: Upload an mp3 file to Restful WCF service
Server side method:
[WebInvoke]
public string RecieveMp3(Stream mp3Stream)
{
byte[] buffer = new byte[5000000];
using (FileStream ms = new FileStream("C:\\Temp\\Test1.mp3", FileMode.OpenOrCreate))
{
int read = mp3Stream.Read(buffer, 0, buffer.Length);
ms.Write(buffer, 0, read);
}
return "Recieved Mp3 file";
}
NOTE:
1. Make sure that you have permissions on the folder to write the mp3 file for the user associated with the app pool under which the wcf service is running
2. For testing purpose i have hard coded the byte array size to be a large value.
Client to call the service:
private string UseRestSharpApproachForFiles(string serviceBaseUrl, string resourceUrl, Method method, string filepath)
{
var client = new RestClient();
client.BaseUrl = serviceBaseUrl;
var request = new RestRequest(method) { DateFormat = DataFormat.Xml.ToString(), Resource = resourceUrl };
request.AddFile("stream", filepath);
var response = client.Execute(request);
string responseString;
if (response.StatusCode == HttpStatusCode.OK)
{
responseString = HttpUtility.HtmlDecode(response.Content);
}
else
{
responseString = response.StatusDescription + " --------------------" + HttpUtility.HtmlDecode(response.Content);
}
return responseString;
}
Am using the 3rd party dll for invoking the rest service called RestSharp.
I tried to Serialize cookie to save it and Deserialize at next time I start my application.But the result of Deserialize is empty.What's wrong?
void SaveCookie() {
var appStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (this.checkBox_save_passowrd.IsChecked == true)
{
CookieContainer cc = SEC_Services.Httprequest.cookie;
string fileName = "usercookie.xml";
using (var file = appStorage.OpenFile(fileName, System.IO.FileMode.OpenOrCreate, System.IO.FileAccess.Write))
{
using (var writer = new StreamWriter(file))
{
System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(CookieContainer));
xs.Serialize(writer, cc);
writer.Close();
}
}
}
else {
if (appStorage.FileExists("usercookie.xml"))
{
appStorage.DeleteFile("usercookie.xml");
}
}
}
void ReadCookie() {
var appStorage = IsolatedStorageFile.GetUserStoreForApplication();
if (appStorage.FileExists("usercookie.xml"))
{
using (System.IO.StreamReader reader = new StreamReader(appStorage.OpenFile("usercookie.xml", FileMode.Open)))
{
System.Xml.Serialization.XmlSerializer xs = new System.Xml.Serialization.XmlSerializer(typeof(CookieContainer));
CookieContainer obj = (CookieContainer)xs.Deserialize(reader);
reader.Close();
SEC_Services.Httprequest.cookie = obj;
if (obj.Count != 0) {
NavigationService.Navigate(new Uri("/PanoramaPage.xaml", UriKind.Relative));
}
}
}
}
I also found this simple
C#: Writing a CookieContainer to Disk and Loading Back In For Use
shows that CookieContainer could be Serialize.But there is no SoapFormatter in wp7 library
IsolatedStorageSettings.ApplicationSettings["index"] = yourcookie;
So you don't need to serialize it.
I'm using it in a project
As the question is "How to Serialize CookieContainer" and the accepted answer doesn't really answer this. This is how to do it with serialization:
Write to disk:
public static void WriteCookiesToDisk(string file, CookieContainer cookieJar)
{
using(Stream stream = File.Create(file))
{
try {
Console.Out.Write("Writing cookies to disk... ");
BinaryFormatter formatter = new BinaryFormatter();
formatter.Serialize(stream, cookieJar);
Console.Out.WriteLine("Done.");
} catch(Exception e) {
Console.Out.WriteLine("Problem writing cookies to disk: " + e.GetType());
}
}
}
Read from disk:
public static CookieContainer ReadCookiesFromDisk(string file)
{
try {
using(Stream stream = File.Open(file, FileMode.Open))
{
Console.Out.Write("Reading cookies from disk... ");
BinaryFormatter formatter = new BinaryFormatter();
Console.Out.WriteLine("Done.");
return (CookieContainer)formatter.Deserialize(stream);
}
} catch(Exception e) {
Console.Out.WriteLine("Problem reading cookies from disk: " + e.GetType());
return new CookieContainer();
}
}