How to download an image only if it's not existing already? - c#

I am writing a program that displays usercontrols in a flowlayout panel. The user layout has images, which are downloaded by the program.
For speeding up, the program should check, if the image to download already exists at the download location. If it exists, it may not download it again.
I am using this code.
WebClient wcGreatest = new WebClient();
Uri url = client.GetImageUrl(client.Config.Images.PosterSizes.Last(), searchSerie.PosterPath);
byte[] imageData = wcGreatest.DownloadData(url);
MemoryStream stream = new MemoryStream(imageData);
seriePopular.btnSerie.Image = Image.FromStream(stream);
stream.Close();

if (File.Exists(pathPoster + fileName))
{
seriePopular.btnSerie.Image = Image.FromFile(pathPoster + fileName);
}
else
{
Uri url = client.GetImageUrl(client.Config.Images.PosterSizes.Last(), searchSerie.PosterPath);
byte[] imageData = wcGreatest.DownloadData(url);
File.WriteAllBytes(pathPoster + fileName, imageData);
seriePopular.btnSerie.Image = Image.FromFile(pathPoster + fileName);
}

Related

How to solve 'Could not find a part of the path..' issue on server

I'm using Zxing library to create a barcode and memory stream to save it to the server folder.
Everything works fine on local as well as a testing server, but when I publish code on client-server it won't create a barcode image nor get location of image on that server location.
Here is the code I created for this process-
var writer = new BarcodeWriter();
writer.Format = BarcodeFormat.CODE_128;// QR_CODE;
var result = writer.Write(printArray[0]);
string path = Server.MapPath("/images/code/" + ComplaintId + ".jpg");
var barcodeBitmap = new Bitmap(result);
using (MemoryStream memory = new MemoryStream())
{
using (FileStream fs = new FileStream(path, FileMode.Create, FileAccess.ReadWrite))
{
barcodeBitmap.Save(memory, ImageFormat.Jpeg);
byte[] bytes = memory.ToArray();
fs.Write(bytes, 0, bytes.Length);
}
}
This code is used to save bar code on the server location.
string ImagePath = ComplaintId + ".jpg";
imgQRcode.Src = "~/images/code/" + ImagePath;
and used this line to bind it to img tag.
it shows error like
Could not find a part of the path g:\xyz\images\code\103.jpg
this only happen on client-server not elsewhere.
---------Edit 1--------
As I was still facing issues while creating image on a host server, I made a few changes in code now. Instead of saving barcode image I'm converting it to Base64 string and using it.
Here is code changes
var barWriter = new BarcodeWriter();
barWriter.Format = BarcodeFormat.CODE_128;// QR_CODE;
var barResult = barWriter.Write("printbar");
var barcodeBitmap = new Bitmap(barResult);
string bs64 = ToBase64String(barcodeBitmap, ImageFormat.Jpeg);
and Tobase64String function
public static string ToBase64String(Bitmap bmp, ImageFormat imageFormat)
{
string base64String = string.Empty;
MemoryStream memoryStream = new MemoryStream();
bmp.Save(memoryStream, imageFormat);
memoryStream.Position = 0;
byte[] byteBuffer = memoryStream.ToArray();
memoryStream.Close();
base64String = Convert.ToBase64String(byteBuffer);
byteBuffer = null;
return base64String;
}
and function to bind base64 to image
public static string GetImageSrc(string base64Src)
{
return "data:image/png;base64," + base64Src;
}
to feed it to iTextcharp use
byte[] imageBytes = Convert.FromBase64String(bs64);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imageBytes);

Download zip file to big(400 MB) in MVC

The following code works well with small files, like 100MB, but it throws a System.OutOfMemoryException for bigger files, like 400MB. I'm using the NotNetZip as dll to get file as zip.
This is my code:
string pathGetDoc = pathDocs + "\\" + informe.NickName + "\\" + getMesActual() + "\\" + informe.Name;
string fileName = informe.Name;
System.Net.WebClient wc = new System.Net.WebClient();
wc.OpenRead(pathGetDoc);
int bytes_total = Convert.ToInt32(wc.ResponseHeaders["Content-Length"].ToString());
if(bytes_total >= 100000000)
{
using (ZipFile zip = new ZipFile())
{
zip.AddFile(pathGetDoc, fileName);
zip.CompressionMethod = CompressionMethod.BZip2;
zip.CompressionLevel = Ionic.Zlib.CompressionLevel.BestCompression;
using (MemoryStream memoryStream = new MemoryStream())
{
zip.Save(memoryStream);
return File(memoryStream.ToArray(), "application/zip", "z.zip");
}
}
}
As you can see, I have a IF to check the size of the file, this work good but when the process goes to save .zip file, I have the error System.OutOfMemoryException

C# TagLib Set Album Cover for Mp3

I have an mp3 file and I want to add the album art to it. The art has been saved into a temp folder, I have check this and it is there and is a jpeg.
This is the code I gave:
public void AddMp3Tags()
{
TagLib.File file = TagLib.File.Create(OutputPath + OutputName + "." + Format);
SetAlbumArt(Art, file);
file.Tag.Title = SongTitle;
file.Tag.Performers = Artists.Split(',');
file.Tag.Album = Album;
file.Tag.Track = (uint)TrackNumber;
file.Tag.Year = (uint)Convert.ToInt32(Regex.Match(Year, #"(\d)(\d)(\d)(\d)").Value);
file.Save();
}
public void SetAlbumArt(string url, TagLib.File file)
{
string path = string.Format(#"{0}temp\{1}.jpg", OutputPath, Guid.NewGuid().ToString());
using (WebClient client = new WebClient())
{
client.DownloadFile(new Uri(url), path);
}
TagLib.Picture pic = new TagLib.Picture
{
Type = TagLib.PictureType.FrontCover,
Description = "Cover",
MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg
};
MemoryStream ms = new MemoryStream();
Image image = Image.FromFile(path);
image.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
ms.Position = 0;
pic.Data = TagLib.ByteVector.FromStream(ms);
file.Tag.Pictures = new TagLib.IPicture[] { pic };
file.Save();
ms.Close();
}
All of the tags are set correctly except the art work which just shows a black box:
Black box cover art in windows media player.
I have tried many things, what am I doing wrong?
So I did some more research and it turns out that by default WMP tries to use a web service to get album artwork, I opened the song in VLC and the artwork was shown. The album code was correctly written as shown here: Mp3Tag Viewer/Editor
Another thing that I found out is that my tags were using Id3v2.4 and Id3v1. WMP does not like this for some reason so I forced TagLib to use Id3v2.3. I also changed the text encoding to UFT16 because UFT8 wasn't working. The album art is now showing in WMP and windows explorer.
I also found a way not to write the image to the disk by downloading the data from the web page and saving it to memory.
This was my final code:
public void AddMp3Tags()
{
TagLib.Id3v2.Tag.DefaultVersion = 3;
TagLib.Id3v2.Tag.ForceDefaultVersion = true;
TagLib.File file = TagLib.File.Create(OutputPath + OutputName + ".mp3");
SetAlbumArt(Art, file);
file.Tag.Title = SongTitle;
file.Tag.Performers = Artists.Split(',');
file.Tag.Album = Album;
file.Tag.Track = (uint)TrackNumber;
file.Tag.Year = (uint)Convert.ToInt32(Regex.Match(Year, #"(\d)(\d)(\d)(\d)").Value);
file.RemoveTags(file.TagTypes & ~file.TagTypesOnDisk);
file.Save();
}
public void SetAlbumArt(string url, TagLib.File file)
{
string path = string.Format(#"{0}temp\{1}.jpg", OutputPath, Guid.NewGuid().ToString());
byte[] imageBytes;
using (WebClient client = new WebClient())
{
imageBytes = client.DownloadData(url);
}
TagLib.Id3v2.AttachedPictureFrame cover = new TagLib.Id3v2.AttachedPictureFrame
{
Type = TagLib.PictureType.FrontCover,
Description = "Cover",
MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg,
Data = imageBytes,
TextEncoding = TagLib.StringType.UTF16
};
file.Tag.Pictures = new TagLib.IPicture[] { cover };
}
I hope this helps anyone that has the same problem as me and doesn't need to spend as much time figuring this out as I did.
Make sure your file downloaded successfully and try this:
public void SetAlbumArt(string url, TagLib.File file)
{
string path = string.Format(#"{0}temp\{1}.jpg", OutputPath, Guid.NewGuid().ToString());
using (WebClient client = new WebClient())
{
client.DownloadFile(new Uri(url), path);
}
file.Tag.Pictures = new TagLib.IPicture[]
{
new TagLib.Picture(new TagLib.ByteVector((byte[])new System.Drawing.ImageConverter().ConvertTo(System.Drawing.Image.FromFile(path), typeof(byte[]))))
{
Type = TagLib.PictureType.FrontCover,
Description = "Cover",
MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg
}
};
file.Save();
}

Setting System.Uri from android uri string xamarin

I have a camerapage which takes a picture, resizes it to a thumbnail and saves this resized image to a file locally on the android phone. I then try to send this uri-string to a viewmodel which is supposed to set its ImageSource property from this uri. I am currently unable to load the image from the url.
Here is my code:
In CameraPage(inside Take photo method)
var documentsPath = System.Environment.GetFolderPath(System.Environment.SpecialFolder.Personal);
using (var imageStream = new MemoryStream())
{
await image.CompressAsync(Bitmap.CompressFormat.Jpeg, 40, imageStream);
image.Recycle();
imageBytes = imageStream.ToArray();
var thumbnail =await DependencyService.Get<IPicResizer>().GetResizedImage(imageBytes);
// Temporary file to store the downloaded image
Java.IO.File tmpFile = new Java.IO.File(documentsPath + "/"+fileName + ".jpg");
tmpFile.ParentFile.Mkdirs();
// String path = MediaStore.Images.Media.InsertImage(this.Context.ContentResolver, documentsPath, fileName, ""); //(this.Context.ContentResolver, image, imgName.ToString(), null);
uri = Android.Net.Uri.Parse(tmpFile.Path);
// The FileOutputStream to the temporary file
var fOutStream = new FileOutputStream(tmpFile);
try
{
fOutStream.Write(thumbnail, 0, thumbnail.Length);
fOutStream.Flush();
fOutStream.Close();
DialogService.HideLoading();
DialogService.ShowSuccess("Saved picture at: " + uri.ToString());
}
catch (Java.IO.FileNotFoundException ex)
{
DialogService.ShowError(ex.InnerException.Message);
}
catch (Java.IO.IOException ex)
{
DialogService.ShowError(ex.InnerException.Message);
}
camera.StartPreview();
await App.Current.MainPage.Navigation.PushModalAsync(new InfoPage(imageBytes, tmpFile.AbsolutePath), false);
}
InfoPages view model:
ImageSource Source {get;set;}
public InfoViewModel(byte[] image, string imageUri)
{
if (image != null)
{
_image = image;
imageurl = new Uri("file:///" + imageUri, UriKind.Absolute);
Source = ImageSource.FromUri(imageurl);
}
}
All help is appreciated :)

Convert file received from jquery to byte array

I need help in converting a file received from a jquery ajax to byte array. I'm using a plugin called ajaxfileupload then from a jquery ajax call I send a file from a fileupload control to a handler. Here is my
handler code:
if (context.Request.Files.Count > 0)
{
string path = context.Server.MapPath("~/Temp");
if (!Directory.Exists(path))
Directory.CreateDirectory(path);
var file = context.Request.Files[0];
string fileName;
if (HttpContext.Current.Request.Browser.Browser.ToUpper() == "IE")
{
string[] files = file.FileName.Split(new char[] { '\\' });
fileName = files[files.Length - 1];
}
else
{
fileName = file.FileName;
}
string fileType = file.ContentType;
string strFileName = fileName;
FileStream fs = new FileStream("~/Temp/" + strFileName, FileMode.Open, FileAccess.Read);
BinaryReader br = new BinaryReader(fs);
Byte[] imagebytes = br.ReadBytes((Int32)fs.Length);
br.Close();
fs.Close();
DBAccess dbacc = new DBAccess();
dbacc.saveImage(imagebytes);
string msg = "{";
msg += string.Format("error:'{0}',\n", string.Empty);
msg += string.Format("msg:'{0}'\n", strFileName);
msg += "}";
context.Response.Write(msg);
}
I'm saving the file to a folder within a project then trying to retrieve that file and save it to the database. I can assure you that the image is being saved to the temp folder. The problem is with the line with (*) the file path is wrong. This is the file path that is being retrieved. "'C:\Program Files\Common Files\Microsoft Shared\DevServer\10.0\~\Temp\2012-06-03 01.25.47.jpg'.". The temp folder is located locally inside my project and I want to retrieved the image within that folder. How can I set the file path to my desired location? Or is there another way to convert a file to byte array after retrieving it from a jquery ajax call?
Credits to these articles:
Save and Retrieve Files from SQL Server Database using ASP.NET
Async file upload with jQuery and ASP.NET
Just these 3 lines will do:
int filelength = file.ContentLength;
byte[] imagebytes = new byte[filelength ];
file.InputStream.Read(imagebytes , 0, filelength );
using (var stream = upload.InputStream)
{
// use stream here: using StreamReader, StreamWriter, etc.
}

Categories

Resources