Images in Picturebox c# - c#

I'm writing a program about trying different images in picturebox, but the image must correspond to the text. Plus it must come from "Resources" folder of the project.
this is what i want to do if the text "apple" displays to the screen then the image with a filename "apple" would also display in the picturebox..
I can do it in "if-else" like this
string word="apple";
if(word==apple)
pictureBox1.Image= WindowsFormsApplication4.Properties.Resources.apple;
but What if I have a thousand images, I still think there's an easy way for this,..
i'm trying this one,,
string word=label1.Text;//label1.text changes from time to time
pictureBox1.Image= WindowsFormsApplication4.Properties.Resources.word;
but I know "word" is string....It's not possible...I cannot append string to the syntax....

You can pass in a string using the GetObject method of the ResourceManager class:
string itemName = label1.Text;
this.pictureBox1.Image =
(Image)Properties.Resources.ResourceManager.GetObject(itemName);

If you open resources .Designer.cs file code , you will see something like:
internal static System.Drawing.Bitmap apple {
get {
object obj = ResourceManager.GetObject("apple", resourceCulture);
return ((System.Drawing.Bitmap)(obj));
}
}
so you can do the same thing:
string word=label1.Text;//label1.text changes from time to time
pictureBox1.Image= (System.Drawing.Bitmap)WindowsFormsApplication4
.Properties
.Resources
.ResourceManager.GetObject(word);

Related

How to put text file content to dictionary c# unity

I have a few text files with phrases in them(answers).In a text file for example I have 150 phrases.I am working on a fishing game.After you catch a fish, a reply appears(which comes from the text file) and appears in the middle of the screen.I thought that if I put my text file in the Assets folder then everything will be fine.But no!!! :(
Here is my code where I return my line(answer):
public string filename333 = "try.txt";
public string getRandomMessagefromRechin()
{
var sr = new StreamReader(Application.dataPath + "/" + fileName1);
var fileContents = sr.ReadToEnd();
sr.Close();
var mydata = fileContents.Split("\n"[0]);
var myrandom = Random.Range(1, mydata.Length);
return mydata[myrandom];
}
On PC , when i hit PLAY button , it s working fine,here is an image:
Sorry for the text , it's a random line from my text file.The problem is after I build the project on a tablet or android phone. The answers from my text files are not showing on my screen.
I want to try another method with dictionaries or with a list of strings, but how can I put 150+ lines on a list from the text in a file?
I have another questions:
1.Why isn't my method working?(I suppose that my text files aren't being built, or aren't put in the right folder of the project)
2.Is another method which I can try to load my lines(answers)?
3.As this problem, I have another scene.After you catch a gold fish, a transition appears(screen go black, then screen goes back to normal) and a wheel of luck appears when u can play, like a roulette.This scene isn't loading on my android devices. Why?
It needs to be in the Resources folder. Unity will treat it as a "TextAsset".
It will be readonly once you build.
You will want to use a function like this to split the contents of the file on New Lines and return a list of strings.
private List<string> TextAssetToList(TextAsset ta) {
return new List<string>(ta.text.Split(System.Environment.NewLine));
}
You will also need to load it like other resources
TextAsset myTxt = Resources.Load("try") as TextAsset;
List<string> strLines = TextAssetToList(myTxt);

Creating files using c#, like an evernote

I currently am making a UI for a note keeper and was just going to preview documents etc, but i was wondering what file type i would need to create if instead i wanted to do things like tag the file etc, preferably in c#, basically make my own evernote, how do these programs store the notes?
I dont know how to directly tag the file, but you could create your own system to do it. I mentioned two ways to do it:
The first way is to format the note's / file's contents so that there are two parts, the tags and the actual text. When the program loads the note / file, it seperates the tags and the text. This has the downside that the program have to load the whole file to just find the tags.
The second way is to have a database with the filename and it's associated tags. In this way the program doesn't have to load the whole file just to find the tags.
The first way
In this solution you need to format your files in a specific way
<Tags>
tag1,tag2,tag3
</Tags>
<Text>
The text you
want in here
</Text>
By setting up the file like this, the program can separate the tags from the text. To load it's tags you'd need this code:
public List<string> GetTags(string filePath)
{
string fileContents;
// read the file if it exists
if (File.Exists(filePath))
fileContents = File.ReadAllText(filePath);
else
return null;
// Find the place where "</Tags>" is located
int tagEnd = fileContents.IndexOf("</Tags>");
// Get the tags
string tagString = fileContents.Substring(6, tagEnd - 6).Replace(Environment.NewLine, ""); // 6 comes from the length of "<Tags>"
return tagString.Split(',').ToList();
}
Then to get the text you'd need this:
public string GetText(string filePath)
{
string fileContents;
// read the file if it exists
if (File.Exists(filePath))
fileContents = File.ReadAllText(filePath);
else
return null;
// Find the place where the text content begins
int textStart = fileContents.IndexOf("<Text>") + 6 + Environment.NewLine.Length; // The length on newLine is neccecary because the line shift after "<Text>" shall NOT be included in the text content
// Find the place where the text content ends
int textEnd = fileContents.LastIndexOf("</Text>");
return fileContents.Substring(textStart, textEnd - textStart - Environment.NewLine.Length); // The length again to NOT include a line shift added earlier by code
}
Then I'll let you find out how you do the rest.
The second way
In this solution you have a database file over all your files and their associated tags. This database file would look like this:
[filename]:[tags]
file.txt:tag1, tag2, tag3
file2.txt:tag4, tag5, tag6
The program will then read the file name and the tags in this way:
public static void LoadDatabase(string databasePath)
{
string[] fileContents;
// End process if database doesn't exist
if (File.Exists(databasePath))
return;
fileContents = File.ReadAllLines(databasePath); // Read all lines seperately and put them into an array
foreach (string str in fileContents)
{
string fileName = str.Split(':')[0]; // Get the filename
string tags = str.Split(':')[1]; // Get the tags
// Do what you must with the information
}
}
I hope this helps.

How to manually store image in (database) table in Visual Studio 2012 and retrieve using jQuery Ajax in ASP.NET MVC

My database table
First I tried storing images with datatype image/varbinary but I get an error:
Invalid Value The changed value in this cell was not recognized as being valid. .Net Framework Data Type: Byte[] Error Message: You cannot use the result pane to set this Field data to values other than NULL Type a value appropriate for the data type or press ESC to cancel the change
How can I store image in my database table manually and retrieve them through jQuery Ajax method?
use in C# Button Submit with data source
if (FileUpload1.PostedFile != null && FileUpload1.PostedFile.FileName != null)
{
byte[] img = new byte[Request.Files[0].ContentLength];
Request.Files[0].InputStream.Read(img, 0, Request.Files[0].ContentLength);
datasource.Photo = img; --here you can save file to Database
}
for retrieving image from dbserver use belowed
img.ImageUrl = "data:image/jpg;base64," + Convert.ToBase64String(Upprofile.Photo);
Have you ever tried other ways to store images ?
I have never used such a way to store image in database if you want my two cents it would be better to save your image on host and save its url in the database.
You only need url to show picture in browser...!
I'm not sure if this works in VS2012, but you can try this approach that I'm using in my MVC projects:
public action UploadFile(HttpPostedFileBase file) //this is how you get the file that was submited from your form
{
//so now that I have the file, i need to save it somewhere
//let's see if we have a folder for that, if not let's create it
if(!Directory.Exists(Server.MapPath("~/The path from the root of the app to the uploaded files folder/")))
{
Directory.CreateDirectory(Server.MapPath("~/The path from the root of the app to the uploaded files folder/"));
} //the ~ symbol is part of the code, it returns the physical path to the root of the application
var storage = Server.MapPath("~/The path from the root of the app to the uploaded files folder/");
//now we need a name, we can generate one as a GUID for example, or we can get it's own.
var fileName = file.FileName.Substring(file.FileName.LastIndexOf("\"), file.Name.Length + 1);
//Now you might have to play a bit with the substring arguments, I'm not sure i wrote that right,
//it might not need the +1 part, or it might need it on the LastIndexOf as well,
//anyway, now we have the name and the folder where to save our file, let's do that:
path = String.Format("{0}\{1}", storage, filename);
try
{
file.SaveAs(path); //Now the file is on the server,
//just save this path and whatever else you need in the database so you can
//grab it later.
}
catch
{
//do your exception handling here
}
Saving to database here...
}
In order to grab it you just get that object from the database like any other objects like so:
Let's presume you're doing everything in your controller, which you shouldn't,
public Action GetFile(int id)
{
using(context = new YourDbContext())
{
var file = context.Files.FirstOrDefault(p => p.Id == id);
}
return View(file);
}
And put it's path for the src in html to show the image like so:
<img src="#Model.path" /> //Considering that in your controller you will `return View(file);`
//So your file object is the model.
One more thing, I'm not sure if in paths you'll need \ or /, I always get it wrong the first time so debug it on the first run and if your path looks likeFolder1Folder2Folder3File it means you need to change it :).
I hope this helped, good luck.
P.S., there might be better ways to do it, but this is how I'm doing it and it seams to work fine for me.
On server, you convert image to a base64 string and save to database.
using (Image image = Image.FromFile(Path))
{
using (MemoryStream m = new MemoryStream())
{
image.Save(m, image.RawFormat);
byte[] imageBytes = m.ToArray();
// Convert byte[] to Base64 String
string base64String = Convert.ToBase64String(imageBytes);
return base64String;
}
}
Beside Client, you put base64 string in Image object
var image = new Image();
image.src = 'data:image/png;base64,your base64 string';
document.body.appendChild(image);
I think store image on the disk better.

Load image from resources area of project in C#

I have an image in my project stored at Resources/myimage.jpg. How can I dynamically load this image into Bitmap object?
Are you using Windows Forms? If you've added the image using the Properties/Resources UI, you get access to the image from generated code, so you can simply do this:
var bmp = new Bitmap(WindowsFormsApplication1.Properties.Resources.myimage);
You can get a reference to the image the following way:
Image myImage = Resources.myImage;
If you want to make a copy of the image, you'll need to do the following:
Bitmap bmp = new Bitmap(Resources.myImage);
Don't forget to dispose of bmp when you're done with it. If you don't know the name of the resource image at compile-time, you can use a resource manager:
ResourceManager rm = Resources.ResourceManager;
Bitmap myImage = (Bitmap)rm.GetObject("myImage");
The benefit of the ResourceManager is that you can use it where Resources.myImage would normally be out of scope, or where you want to dynamically access resources. Additionally, this works for sounds, config files, etc.
You need to load it from resource stream.
Bitmap bmp = new Bitmap(
System.Reflection.Assembly.GetEntryAssembly().
GetManifestResourceStream("MyProject.Resources.myimage.png"));
If you want to know all resource names in your assembly, go with:
string[] all = System.Reflection.Assembly.GetEntryAssembly().
GetManifestResourceNames();
foreach (string one in all) {
MessageBox.Show(one);
}
Way easier than most all of the proposed answers
tslMode.Image = global::ProjectName.Properties.Resources.ImageName;
The best thing is to add them as Image Resources in the Resources settings in the Project. Then you can get the image directly by doing Resources.myimage. This will get the image via a generated C# property.
If you just set the image as Embedded Resource you can get it with:
string name = "Resources.myimage.jpg"
string namespaceName = "MyCompany.MyNamespace";
string resource = namespaceName + "." + name;
Type type = typeof(MyCompany.MyNamespace.MyTypeFromSameAssemblyAsResource);
Bitmap image = new Bitmap(type.Assembly.GetManifestResourceStream(resource));
Where MyTypeFromSameAssemblyAsResource is any type that you have in your assembly.
Code I use in several of my projects...
It assumes that you store images in resource only as bitmaps not icons
public static Bitmap GetImageByName(string imageName)
{
System.Reflection.Assembly asm = System.Reflection.Assembly.GetExecutingAssembly();
string resourceName = asm.GetName().Name + ".Properties.Resources";
var rm = new System.Resources.ResourceManager(resourceName, asm);
return (Bitmap)rm.GetObject(imageName);
}
Use below one. I have tested this with Windows form's Grid view cell.
Object rm = Properties.Resources.ResourceManager.GetObject("Resource_Image");
Bitmap myImage = (Bitmap)rm;
Image image = myImage;
Name of "Resource_Image", you can find from the project.
Under the project's name, you can find Properties. Expand it. There you can see Resources.resx file. Open it. Apply your file name as "Resource_Image".
JDS's answer worked best. C# example loading image:
Include the image as Resource (Project tree->Resources, right click to add the desirable file ImageName.png)
Embedded Resource (Project tree->Resources->ImageName.png, right click select properties)
.png file format (.bmp .jpg should also be OK)
pictureBox1.Image = ProjectName.Properties.Resources.ImageName;
Note the followings:
The resource image file is "ImageName.png", file extension should be omitted.
ProjectName may perhaps be more adequately understood as "Assembly name", which is to be the respective text entry on the Project->Properties page.
The example code line is run successfully using VisualStudio 2015 Community.
I suggest:
System.Reflection.Assembly thisExe;
thisExe = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream file =
thisExe.GetManifestResourceStream("AssemblyName.ImageFile.jpg");
Image yourImage = Image.FromStream(file);
From msdn:
http://msdn.microsoft.com/en-us/library/aa287676(v=vs.71).aspx
Using Image.FromStream is better because you don't need to know the format of the image (bmp, png, ...).
With and ImageBox named "ImagePreview
FormStrings.MyImageNames contains a regular get/set string cast method, which are linked to a scrollbox type list.
The images have the same names as the linked names on the list, except for the .bmp endings.
All bitmaps are dragged into the resources.resx
Object rm = Properties.Resources.ResourceManager.GetObject(FormStrings.MyImageNames);
Bitmap myImage = (Bitmap)rm;
ImagePreview.Image = myImage;
In my case -- I was using Icons in my resource, but I needed to add them dynamically as Images to some ToolStripMenuItem(s). So in the method that I created (which is where the code snippet below comes from), I had to convert the icon resources to bitmaps before I could return them for addition to my MenuItem.
string imageName = myImageNameStr;
imageName = imageName.Replace(" ", "_");
Icon myIcon = (Icon)Resources.ResourceManager.GetObject(imageName);
return myIcon.ToBitmap();
Something else to be aware of, if your image/icon has spaces (" ") in its name when you add them to your resource, VS will automatically replace those spaces with "_"(s). Because, spaces are not a valid character when naming your resource. Which is why I'm using the Replace() method in my referenced code. You can likely just ignore that line.
You can also save the bmp in a var like this:
var bmp = Resources.ImageName;
hope it helps!
Strangely enough, from poking in the designer I find what seems to be a much simpler approach:
The image seems to be available from .Properties.Resources.
I'm simply using an image as all I'm interested in is pasting it into a control with an image on it.
(Net 4.0, VS2010.)
I looked at the designer code from one of my projects and noticed it used this notation
myButton.Image = global::MyProjectName.Properties.Resources.max;
where max is the name of the resource I uploaded into the project.
Or you could use this line when dealing with WPF or Silverlight, especially where you have the source string already in the XAML markup:
(ImageSource)new ImageSourceConverter().ConvertFromString(ImagePath);
Where the ImagePath is something like:
string ImagePath = "/ProjectName;component/Resource/ImageName.png";
This is how I manage to create an ImageList from a Resource (.rc) file of a windows forms application:
ImageList imgList = new ImageList();
var resourceSet = DataBaseIcons.ResourceManager.GetResourceSet(CultureInfo.CreateSpecificCulture("en-EN"), true, true);
foreach (var r in resourceSet)
{
Logger.LogDebug($"Resource Type {((DictionaryEntry)r).Key.ToString()} is of {((DictionaryEntry)r).Value.GetType()}");
if (((DictionaryEntry)r).Value is Bitmap)
{
imgList.Images.Add(((Bitmap)(((DictionaryEntry)r).Value)));
}
else
{
Logger.LogWarning($"Resource Type {((DictionaryEntry)r).Key.ToString()} is of type {((DictionaryEntry)r).Value.GetType()}");
}
}
this.toolStrip1 = new System.Windows.Forms.ToolStrip();
this.toolStrip1.Location = new System.Drawing.Point(0, 0);
this.toolStrip1.Name = "toolStrip1";
this.toolStrip1.Size = new System.Drawing.Size(444, 25);
this.toolStrip1.TabIndex = 0;
this.toolStrip1.Text = "toolStrip1";
object O = global::WindowsFormsApplication1.Properties.Resources.ResourceManager.GetObject("best_robust_ghost");
ToolStripButton btn = new ToolStripButton("m1");
btn.DisplayStyle = ToolStripItemDisplayStyle.Image;
btn.Image = (Image)O;
this.toolStrip1.Items.Add(btn);

get Image object from path name

Given a path and filename how can I get the Image object:
Image image = ...(filename)
You want to call the static FromFile method on the Image class.
Another alternative is to use a Bitmap object (which inherits from Image) like so:
Bitmap bitmap = new Bitmap(imagePath);
(This works for all image formats, not just *.bmp as the name might imply.)
If you're playing with images in memory, I've found that bobpowell.net has a GREAT site for GDI work in C#.
No.. I'm not related to, associated with or hired by Bob Powell. I just really enjoy his work. =)
// Get original filename with extention
string filenameWithPath = "C:\pictures\peanutbutterjellytime.jpg;
filename = System.IO.Path.GetFileName(filenameWithPath);
Also, if you're having trouble getting the path of the resource (trickiest part) you can do a :
Assembly myAssembly = Assembly.GetExecutingAssembly();
string[] names = myAssembly.GetManifestResourceNames();
foreach (string name in names)
{
Console.WriteLine( name );
}
Which shows all paths for resources.

Categories