Resizing gif images using Imageresizer - c#

I attempted to use imageresizer and the animated gif plugin to resize an animated gif. It did resize but I lost the animation in the process. I did set the format to gif even after following the example given on the site. Any help would be appreciated.
Thanks for the response. I should first point out that I am building a desktop application. Here is the code I am using:
var fileName = ofdChiImage.FileName;
Dictionary<string, string> versions = new Dictionary<string, string>();
versions.Add("_thumb1", "maxwidth=200&maxheight=200&format=gif");
string basepath = ImageResizer.Util.PathUtils.RemoveExtension(fileName);
foreach (string suffix in versions.Keys)
{
ImageBuilder.Current.Build(fileName, basepath + suffix, new ResizeSettings(versions[suffix]), false, true);
}

in .NET4+, Console and desktop applications do not automatically load DLLs that are not explicitly referenced through code (even if they are referenced within App.config). Thus for these types of applications we always recommend the code-based (instead of xml-based) installation method for ImageResizer plugins.

Related

Resize Image (jpg) in Blazor WebAssembly?

What is the best way to resize an image that is uploaded on a Blazor client page. These are real simple images that I just wanted to have a consistent width and was hoping to use the System.Drawing, but that is not available in web assembly. I was hoping to do it on the client, but is it best to send it to a Controller for processing?
Thanks,
Mike
.NET 5 has an extension method to IBrowserFile called RequestImageFileAsync. Per the documentation, it "Attempts to convert the current image file to a new one of the specified file type and maximum file dimensions."
We use a package PhotoSauce.MagicScaler for all images uploaded from any blazor page.
https://photosauce.net/
I have no affiliation with this package / author etc. Just recommend it because it works so well.
There are lots of params that you can set in the ProcessImageSettings for width, method of resizing etc.
var settings = new ProcessImageSettings { Height = 250 };
using var outStream = new FileStream(thumbNailPathAndFile, FileMode.Create);
MagicImageProcessor.ProcessImage(pathAndFile, outStream, settings);

Xamarin Forms: Default Image if Url not found

In xamarin forms we can create images like this:
Image i = new Image { Source = "http://www.foo.com/foo.jpg };
After adding this to layout if url returns an image it will display it. What I want to now is is there a way to know if ths Url is an actual image. Otherwise I am going to show an default image.
Regards.
Edit
I have created a function:
public string GetImageSourceOrDefault(string orgUrl)
{
var req = (HttpWebRequest)WebRequest.Create(orgUrl);
req.Method = "HEAD";
try
{
using (var resp = req.GetResponse())
{
bool res = resp.ContentType.ToLower(CultureInfo.InvariantCulture)
.StartsWith("image/");
if (res)
return orgUrl;
else
return "defualt_logo.jpg";
}
}
catch
{
return "default_logo.jpg";
}
}
This function does the trick. However, for every image it does a request. I have a listview which shows like 220 entries. Using this method messed up the time that listview gets loaded.
Note: this function is natively called using dependency injection.
Maybe further improvements will do. Any ideas?
FFImageLoading CachedImage supports Loading and Error Placeholders (and much more). It's basically a API compatible replacement for Image with additional properties. You could try that.
var cachedImage = new CachedImage() {
LoadingPlaceholder = "Loading.png",
ErrorPlaceholder = "Error.png"
};
https://github.com/molinch/FFImageLoading
With Xamarin.Forms UriImageSource you can specify different caching length, and whether caching is used by using the properties CacheValidity and CachingEnabled.
By default it will automatically cache results for 1 day on the local storage of the device.
In your function, as you mention, you are downloading the image every single time.
You have no current functionality that is storing and caching the result for later re-use.
By implementing something like this on the platform specific layer would get around your current solution of re-downloading the image every single time.
Alternatively as a workaround, if you didn't want to implement the above, you could try putting two Image controls stacked upon each other, maybe in a Grid, with the bottom image showing a default placeholder image, and on-top another Image control that would show the intended image, if successfully downloaded, using the UriImageSource.
You could also possibly hook hook into the PropertyChange notification of the Image.Source and detect it being set, with the image then being displayed. Upon detection you could then release the image from the temporary place holder Image control perhaps?

How to get all files list from a relative URI in XAML application?

How to get all files from a folder in XAML application using relative path?
I am playing with a Kinect application built in WPF. All images used in the application are in
[project dir]\Images\ and all backgrounds are in
[project dir]\Images\Backgrounds\.
I want to get list of all the images from Backgrounds directory using relative path. I have tried
DirectoryInfo(#"\Images\Backgrounds\").GetFiles();
but it says that Backgrounds directory must exist in [full path+project dir]\debug\bin\
Selecting each image manually works fine
Uri uri = new Uri(#"Images\Backgrounds\Background1.png", UriKind.Relative);
ImageSource imgsource = new BitmapImage(uri);
this.Backdrop.Source = imgsource;
It works for a single file because you specify URI to resource embedded in the assembly and not some folder on your drive, whilst GetFiles() will work only on a specific physical folder. So either you need to copy all your images instead of embedding them or use the code below and resourceNames should give you names of all resources that you can reference by URI in your project:
List<string> resourceNames = new List<string>();
var assembly = Assembly.GetExecutingAssembly();
var rm = new ResourceManager(assembly.GetName().Name + ".g", assembly);
try
{
var list = rm.GetResourceSet(CultureInfo.CurrentCulture, true, true);
foreach (DictionaryEntry item in list)
resourceNames.Add((string)item.Key);
}
finally
{
rm.ReleaseAllResources();
}
if you need then at this point each item.Value contains UnmanagedMemoryStream for each resource.
I would reply to your post instead of posting a solution, but I'm new to this site and dont have that privledge yet.... Hey! Just trying to help.
Anyway, I've had a problem similar to this before concerning DirectoryInfo. Can't remember exactly how I solved it, but I remember the backslashes being tricky. Have you checked out the MSDN site? It seems like it can't find your directory so its looking for it in debug by default. MSDN says the format should be "MyDir\MySubdir" in C#.

GetManifestResourceStream giving Null Reference exception ( Parameter name: streamSource)

I keep on getting a null reference exception from GetManifestResourceStream, am trying to add Logo image to the Lightswitch ribbon and it is supposed to work just fine....
was referring to LR__ http://social.msdn.microsoft.com/Forums/en-US/lightswitch/thread/2d16c638-f833-4c4c-beec-656912a87b8e/#76fa5382-0135-41ba-967c-02efc3f8c3a2
System.Windows.Media.Imaging.BitmapImage image = new System.Windows.Media.Imaging.BitmapImage();
image.SetSource(Assembly.GetExecutingAssembly().GetManifestResourceStream(
Application.Current.Details.Name + ".Resources.logo.jpg"));
Image myImage = new Image()
{
Source = image,
Stretch = System.Windows.Media.Stretch.Uniform,
HorizontalAlignment = HorizontalAlignment.Left,
Margin = new Thickness(2, 2, 2, 14),
Cursor = System.Windows.Input.Cursors.Hand
};
I tried a lot of things but I can't find my where the problem is!!
add your image or file in your project then select your file on the solution explorer window then on the properties window select Build Action then set value "Embedded Resource" to Build Action properties
just this
Does Logo.jpg have it's build action set to "Embedded Resource"?
Edit:
Here the C# translation of my GetResourceUri (note, it needs a Resource, not an Embedded Resource):
public Uri GetResourceUri(this Assembly asm, string resourceName)
{
Uri result = null;
var assemblyName = new AssemblyName(asm.FullName).Name;
result = new Uri(string.Format("/{0};component/{1}", assemblyName, resourceName), UriKind.Relative);
return result;
}
The same "technique" should work in C#.
I also have a custom shell extension (that uses LR's technique to add images to both the ribbon & the navigation menu). I'm just finishing a few things (writing the "documentation" is taking some time) & then I'll release it on the Visual Studio Gallery for the community to use (it's called Luminous Classic Shell).
The extension allows you to have the images without needing to write code.
You can use a tool such as Reflector to see the full names of the resources in the Assembly.
I had this null return problem & I was tearing my hair out because this using image files as embedded resources is one of my standard tricks.
I eventually found the reason was that I'd been sent files from a graphic designer who uses an Apple & they didn't work. I fiddled with permissions; used a Paint program to save them in a different format but nothing worked.
In the end I created a completely new file in Paint, then copied & pasted the pixels from the original image. It then worked.
Just for the record, does anyone know why this happened? It must be in the header blocks somehow.

C# XNA 4.0 Exception: "Cannot Open File"

I am working in XNA 4.0 Game Studio (C#), and I am trying to load an image using the LoadContent() method. I have loaded numerous image files into this game and they all work 100% fine, but for some reason, XNA will not open files inside one of my loadContent methods. Here is the method:
protected override void LoadContent()
{
//spriteBatch = new SpriteBatch(GraphicsDevice);
//Sets up an array of textures to be used in the Icon class
Texture2D[] icons = new Texture2D[24];
#region Loading talent textures
//These are all of the icons that need to be loaded for the talents
//Paladin
icons[0] = Content.Load<Texture2D>(#"C:\Users\Student\Desktop\Dropbox\Public\platformer\Platformer\Content\Talents\blade_of_light3.jpg");
icons[1] = Content.Load<Texture2D>("Talents\\divine_grace");
icons[2] = Content.Load<Texture2D>("Talents\\divine_storm");
icons[3] = Content.Load<Texture2D>("Talents\\hammer_of_the_righteous");
icons[4] = Content.Load<Texture2D>("Talents\\healing_hands");
icons[5] = Content.Load<Texture2D>("Talents\\heavenly_fury");
icons[6] = Content.Load<Texture2D>("Talents/momentum_of_light");
icons[7] = Content.Load<Texture2D>("Talents/retribution");
icons[8] = Content.Load<Texture2D>("Talents/righteous_fury");
icons[9] = Content.Load<Texture2D>("Talents/sanctuary");
icons[10] = Content.Load<Texture2D>("Talent/searing_light");
icons[11] = Content.Load<Texture2D>("Talent/wrath_of_the_heavens");
//Warrior
icons[12] = Content.Load<Texture2D>(#"Talents\bloodstorm");
icons[13] = Content.Load<Texture2D>(#"Talents\bloodthirst");
icons[14] = Content.Load<Texture2D>(#"Talents\die_by_the_sword");
icons[15] = Content.Load<Texture2D>(#"Talents\furious_blades");
icons[16] = Content.Load<Texture2D>(#"Talents\unleash_rage");
icons[17] = Content.Load<Texture2D>(#"Talents\lifeblood");
icons[18] = Content.Load<Texture2D>(#"Talents\red_like_my_rage");
icons[19] = Content.Load<Texture2D>(#"Talents\eternal_thirst");
icons[20] = Content.Load<Texture2D>(#"Talents\bladesurge");
icons[21] = Content.Load<Texture2D>(#"Talents\bathed_in_blood");
icons[22] = Content.Load<Texture2D>(#"Talents\bladerunner");
icons[23] = Content.Load<Texture2D>(#"Talents\bloodfury");
icons[24] = Content.Load<Texture2D>(#"Talents\grapple_chain");
#endregion
As you can see, I have tried using the ENTIRE file location. It finds the file, but throws an exception when the LoadContent() method is called and says "Cannot open file blade_of_light3."
I do not get any errors about escape paths or anything like that, and I have used this sort of file path for other images, and they work fine. It's just here, in this class, in this loadContent method, that they won't work.
The Content.Load methods does not load files, it loads specialized content or assets. Have a look at this.
You can't load files directly, you can only load assets. These assets are generated via the content pipeline.
This is mainly to provide an abstract layer for content. Because XNA is platform independent, and on one machine you may be use a bigger image or different image, you only need to change the asset in the pipeline and can reuse the code.
Just to add to dowhilefor's excellent answer, if you want to load a raw .jpg file (or .png), you can do so like this:
using(var s = File.OpenRead(fileName))
{
Texture2D texture = Texture2D.FromStream(GraphicsDevice, s);
}
Unlike when you load something using ContentManager, you "own" it in this case. This means you are responsible for calling Dispose() on it in UnloadContent.
Also unlike when you go through the content pipeline (using the default settings), the texture that you load will not have premultiplied-alpha. You need to apply premultiplication yourself, or render it with BlendState.NonPremultiplied.
Of course, unless you are unable to for some reason (eg: you're downloading images from the internet, or you're letting your end user pick them), you should use the content pipeline.

Categories