Loading animated GIFs from resource file in wxWidgets - image

I am trying to embed an animated GIF image into a wxWidgets C++ program. I am able to load the image from file and display it like so:
wxAnimationCtrl *an = new wxAnimationCtrl(this, wxID_ANY, wxAnimation(wxT("image.gif"), wxANIMATION_TYPE_ANY), wxPoint(150,0));
an->Play();
But I would rather have the GIF image in my resource.rc file, so that it is compiled into the executable. How would I do this?

You can try to use wxMSWResources or wxLoadUserResource function, load GIF resource to memory, then obtain wxMemoryInputStream and then use wxAnimation::Load() and pass that input stream to that function

m_ani = new wxAnimationCtrl();
const void* data = NULL;
size_t outLen = 0;
// load the icon directory resource
if ( !wxLoadUserResource(&data, &outLen, "ID_WAIT", RT_RCDATA) )
{
wxLogError(_("Failed to load icons from resource"));
}
else
{
wxMemoryInputStream stream(data, outLen);
if (m_ani->Load(stream)) m_ani->Play();
}

Related

.svg Image in MAUI Blazor

i am trying to set an image in to a razor page in MAUI Blazor.
In MAUI (only), there was the aproach, that you have a .svg image in the folder Resources/Images. MAUI then converts the .svg image in a .png image which you can use in the XAML file. like so:
Now i have the same picture in a MAUI Blazor app and i hoped that i can put my picture in the same way expect that i have to use the HTML style like so:
<img src="one_list2.png">
But this doesn't work at all. I tryed with or witout path, path with slashes, backslashes etc. nothing works.
Trying to put a .png image into the wwwroot folder works. But this isn't the goal. I found it very nice to put a svg image which is then converted into a png depending of its size. This way all pictures would be converted exactly in the perfect size you will need lossless.
Thanks
First, Add the image to Resources\Raw and set it to MauiAsset compilation type
Second, Check the project file to avoid setting the image in the other folder.
In razor component HTML:
<img src="#imageSource">
In the code part:
private string? imageSource;
protected override async Task OnInitializedAsync()
{
try
{
using var stream =
await FileSystem.OpenAppPackageFileAsync("testimage.png");
using var reader = new StreamReader(stream);
byte[] result;
using (var streamReader = new MemoryStream())
{
stream.CopyTo(streamReader);
result = streamReader.ToArray();
}
imageSource = Convert.ToBase64String(result);
imageSource = string.Format("data:image/png;base64,{0}", imageSource);
}
catch (Exception ex)
{
//error
}
}
More information you can refer to ASP.NET Core Blazor Hybrid static files.

Unity - Loading image using www cause all images in application to change

I am pretty new to Unity, so this might be an easy one.
I am trying to load and image from a URL an into an image in my application. In my application I have many different images, but for some reason all the images change to the image loaded from my url.
I have made a component called LoadImage and added it only to the one image I want to change. My code for loading the image looks like this:
public class LoadImage : MonoBehaviour
{
public Image img;
// Use this for initialization
void Start ()
{
DownloadViaURL();
}
void DownloadViaURL()
{
Debug.Log("Called DownloadViaURL");
FirebaseDatabase.DefaultInstance
.GetReference("Child1").Child("Child2").Child("ImageURL")
.GetValueAsync().ContinueWith(task =>
{
Debug.Log("Default Instance entered");
if (task.IsFaulted)
{
Debug.Log("Error retrieving data from server");
}
else if (task.IsCompleted)
{
DataSnapshot snapshot = task.Result;
string data_URL = snapshot.GetValue(true).ToString();
//Start coroutine to download image
StartCoroutine(AccessURL(data_URL));
}
});
}
IEnumerator AccessURL(string url)
{
using (WWW www = new WWW(url))
{
yield return www;
www.LoadImageIntoTexture(img.mainTexture as Texture2D);
Debug.Log("Texture URL: " + www.url);
}
}
}
And I have then added the image as the public Image img;
Can anyone tell my why unity load the image into all imageviews in my application instead of just the one?
You say
I have many different images,
but I guess you mean different Image components where you very probably referenced the same texture from your assets multiple times
So what your code actually does is overwriting whatever texture asset is referenced by your image => it is also changed in all other images/materials etc that reference the same texture asset.
You should rather create a new texture, load the data into it and change the image's texture reference:
// Create new texture
// Size values don't matter because texture will be overwritten
var newTexture = new Texture2D(2,2);
// Load image I new texture
www.LoadImageToTexture(newTexture);
// Use the reference to that new texture
img.mainTexture = newTexture;

Loading a gif from URL in Processing with gifAnimation Library

I am currently trying to load a gif into a processing sketch from a url. I am using the gifAnimation library and when I load a gif stored on my computer it works fine. I just cant seem to get it when I load from url, nothing shows up. Currently I can load the first frame using default Processing like this:
webGif= loadImage(url, "gif");
image(webGif,0,0,720,720);
If I try and load a gif using the library from the url
webGif= new Gif(this, url);
image (webGif, 0 , 0);
webGif.loop();
It doesn't load anything and my program freezes.
Loading a gif from URL seems to work as expected:
import gifAnimation.*;
Gif loopingGif;
public void setup() {
size(400, 200);
frameRate(100);
loopingGif = new Gif(this, "https://s-media-cache-ak0.pinimg.com/originals/1f/d4/83/1fd4831252c28010546e872d5b85bb70.gif");
loopingGif.loop();
}
void draw() {
background(255 / (float)height * mouseY);
image(loopingGif, 10, height / 2 - loopingGif.height / 2);
}
tested with gifAnimation 3.1 using Processing 3.2.3
Also double check the URL is valid and the file is a valid gif, before checking Processing and library versions.

Save WF 4 workflow as Image

The problem is that I am opening workflow designer dynamically from one shell application and I don't have reference to Canvas. I am able to save the WF4 as image but the image is not getting saved properly and contains left & top margins. I followed many articles to get it working but no success. I referred to following article as well.
Saving a canvas to png C# wpf
I am using the below function. I don't have any reference to canvas.
private BitmapFrame CreateWorkflowImage()
{
const double DPI = 96.0;
Visual areaToSave = ((DesignerView)VisualTreeHelper.GetChild(this.wd.View,
0)).RootDesigner;
Rect bounds = VisualTreeHelper.GetDescendantBounds(areaToSave);
RenderTargetBitmap bitmap = new RenderTargetBitmap((int)bounds.Width,
(int)bounds.Height, DPI, DPI, PixelFormats.Default);
bitmap.Render(areaToSave);
return BitmapFrame.Create(bitmap);
}
Please help on this.
I am able to resolve the issue by referring to again the following link
Saving a canvas to png C# wpf
I got the reference to canvas by using following code
Visual canvas= ((DesignerView)VisualTreeHelper.GetChild(this.WorkflowDesigner1.View, 0)).RootDesigner;
This has resolved the border/margin issue.
Please have a look here: http://blogs.msdn.com/b/flow/archive/2011/08/16/how-to-save-wf4-workflow-definition-to-image-using-code.aspx
let’s look at how to generate an image of the workflow definition using the standard mechanism of WPF. After all, workflow designer canvas is a WPF control.
BitmapFrame CreateWorkflowDefinitionImage()
{
const double DPI = 96.0;
// this is the designer area we want to save
Visual areaToSave = ((DesignerView)VisualTreeHelper.GetChild(
this.workflowDesigner.View, 0)).RootDesigner;
// get the size of the targeting area
Rect size = VisualTreeHelper.GetDescendantBounds(areaToSave);
RenderTargetBitmap bitmap = new RenderTargetBitmap((int)size.Width, (int)size.Height,
DPI, DPI, PixelFormats.Pbgra32);
bitmap.Render(areaToSave);
return BitmapFrame.Create(bitmap);
}
The above C# method is very straightforward. Just get the workflow diagram part of the workflow designer and create an in-memory image of it using some WPF API. The next thing is simple: create a file and save the image.
void SaveImageToFile(string fileName, BitmapFrame image)
{
using (FileStream fs = new FileStream(fileName, FileMode.Create))
{
BitmapEncoder encoder = new JpegBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(image));
encoder.Save(fs);
fs.Close();
}
}
At last, let’s try to invoke the above 2 methods in the OnInitialized() method to hook it up and then close the application.
protected override void OnInitialized(EventArgs e)
{
// ...
this.SaveImageToFile("test.jpg", this.CreateWorkflowDefinitionImage());
Application.Current.Shutdown();
}

How do you convert a HttpPostedFileBase to an Image?

I am using ASP.NET MVC and I've an action that uploads the file. The file is being uploaded properly. But I want width and height of the image. I think I need to convert the HttpPostedFileBase to Image first and then proceed. How do I do that?
And please let me know if there is another better way to get the width and height of the image.
I use Image.FromStream to as follows:
Image.FromStream(httpPostedFileBase.InputStream, true, true)
Note that the returned Image is IDisposable.
You'll need a reference to System.Drawing.dll for this to work, and Image is in the System.Drawing namespace.
Resizing the Image
I'm not sure what you're trying to do, but if you happen to be making thumbnails or something similar, you may be interested in doing something like...
try {
var bitmap = new Bitmap(newWidth,newHeight);
using (Graphics g = Graphics.FromImage(bitmap)) {
g.SmoothingMode = SmoothingMode.HighQuality;
g.PixelOffsetMode = PixelOffsetMode.HighQuality;
g.CompositingQuality = CompositingQuality.HighQuality;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(oldImage,
new Rectangle(0,0,newWidth,newHeight),
clipRectangle, GraphicsUnit.Pixel);
}//done with drawing on "g"
return bitmap;//transfer IDisposable ownership
} catch { //error before IDisposable ownership transfer
if (bitmap != null) bitmap.Dispose();
throw;
}
where clipRectangle is the rectangle of the original image you wish to scale into the new bitmap (you'll need to manually deal with aspect ratio). The catch-block is typical IDisposable usage inside a constructor; you maintain ownership of the new IDisposable object until it is returned (you may want to doc that with code-comments).
Saving as Jpeg
Unfortunately, the default "save as jpeg" encoder doesn't expose any quality controls, and chooses a terribly low default quality.
You can manually select the encoder as well, however, and then you can pass arbitrary parameters:
ImageCodecInfo jpgInfo = ImageCodecInfo.GetImageEncoders()
.Where(codecInfo => codecInfo.MimeType == "image/jpeg").First();
using (EncoderParameters encParams = new EncoderParameters(1))
{
encParams.Param[0] = new EncoderParameter(Encoder.Quality, (long)quality);
//quality should be in the range [0..100]
image.Save(outputStream, jpgInfo, encParams);
}
If you are sure, that the source is image and doesn't need editing, you can do it easily as described here
[HttpPost]
public void Index(HttpPostedFileBase file)
{
if (file.ContentLength > 0)
{
var filename = Path.GetFileName(file.FileName);
System.Drawing.Image sourceimage =
System.Drawing.Image.FromStream(file.InputStream);
}
}
To secure the file is image, add javascript validation to View by adding accept attribute with MIME type to input tag
<input type="file" accept="image/*">
and jQuery validation script
$.validator.addMethod('accept', function () { return true; });
The whole solution can be found here

Resources