Loading a Buffered Image - path

I've been trying to figure this out for days. I am trying to load a buffered image from my res directory. My folder hierarchy is.
MainProjectFolder
res
my image to be loaded
src
Logic folder
loop.java(my class to pass a string to BufferedImageLoader to be loaded)
Graphics Folder
BufferedImageLoader.java(converts string to bufferedimage)
However I keep getting a input = null error. How do I point to my image file?
My Loop class
BufferedImageLoader loader = new BufferedImageLoader();
try{
spriteSheet = loader.loadImage("/res/sprite_sheet_test.png");
}catch(IOException e){
e.printStackTrace();
}
My BufferedImageLoaderClass
public BufferedImage loadImage(String path)throws IOException{
url = this.getClass().getResource(path);
image = ImageIO.read(url);
newImage = new BufferedImage(image.getWidth(), image.getHeight(),
BufferedImage.TYPE_INT_ARGB);
Graphics2D g = newImage.createGraphics();
g.drawImage(image, 0, 0, null);
g.dispose();
return newImage;
}
Thanks for your help!!

Given that the folder res is defined as a resource folder in your project and put on class path (and indeed, contains the file sprite_sheet_test.png), this should work:
loader.loadImage("/sprite_sheet_test.png");
Note the leading /, to make sure the image is loaded from the resource root. Without it, the resource would be resolved relative to the package of your BufferedImageLoader class.

Related

Display Image from folder while the path is in Database In RDLC Report

How to Show Pictures of students which is located in folder and the path is in database But I'm unable to Do it I Searched a lot but found nothing useful.
Please help me guys
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
string query = #"select StudentID,c.DocumentType as DocumentID,DocumentNumber,Name,NameDari,FatherName,FatherNameDari,MobileNumber,Photo,b.ClassName as ClassID,d.LocationName as LocationID,e.TeacherName as TeacherID,a.Term,a.Score from StudentsInfo a
join Class b
on a.ClassID=b.ClassID
join Document c
on c.DocumentID=a.DocumentID
join Location d
on d.LocationID=a.LocationID
join Teachers e
on e.TeacherID=a.TeacherID";
var data = db.Database.SqlQuery<StudentsInfo>(query);
ReportViewer1.SizeToReportContent = true;
ReportViewer1.LocalReport.ReportPath = Server.MapPath("Certificates.rdlc");
ReportViewer1.LocalReport.DataSources.Clear();
ReportDataSource ds = new ReportDataSource("Certificates", data);
ReportViewer1.LocalReport.DataSources.Add(ds);
this.ReportViewer1.LocalReport.EnableExternalImages = true;
ReportViewer1.LocalReport.Refresh();
}
}
First, make sure that you're already done these steps in RDLC report designer:
1) Set "External" mode from image source property.
2) Create a report parameter to hold inserted path from code behind by using Add Parameter from context menu.
Then, you can try example below after enabling EnableExternalImages:
this.ReportViewer1.LocalReport.EnableExternalImages = true;
/* begin added part */
// get absolute path to Project folder
string path = new Uri(Server.MapPath("~/path/to/Project/folder")).AbsoluteUri; // adjust path to Project folder here
// set above path to report parameter
var parameter = new ReportParameter[1];
parameter[0] = new ReportParameter("ImagePath", path); // adjust parameter name here
ReportViewer1.LocalReport.SetParameters(parameter);
/* end of added part */
ReportViewer1.LocalReport.Refresh();
Then in report expression editor, define simple expression that concatenates inserted path from ReportParameter and stored path from database (here the parameter name should match with ReportParameter in example code above):
=Parameters!ImagePath.Value + Fields!Photo.Value
References:
How to add an external image in RDLC Report (C#)
Dynamically add and display external Image in RDLC Report from code behind in ASP.Net

Copy asset from bundle to file system

I'm trying to copy an sqlite database from the root bundle onto the file system in order to use it.
I've tried many different ways but it always ended up writing incorrect amounts of data to disk. The code I'm using looks like this:
Directory appDocDir = await getExternalStorageDirectory();
String path = join(appDocDir.path, "data.db");
bool exists = await new File(path).exists();
if (!exists) {
var out = new File(path).openWrite();
var data = await rootBundle.load("assets/data.sqlite");
var list = data.buffer.asUint8List();
out.write(list);
out.close();
}
I was able to do that by the followings.
ByteData data = await rootBundle.load("data.sqlite");
List<int> bytes = data.buffer.asUint8List(data.offsetInBytes, data.lengthInBytes);
Directory appDocDir = await getApplicationDocumentsDirectory()
String path = join(appDocDir.path, "data.db");
await File(path).writeAsBytes(bytes);
You can't write the contents of a Uint8List to a File using IOSink.write (which is designed to operate on String arguments). You'll end up writing the UTF-8 encoded representation of the String obtained by calling toString() on your Uint8List, which is probably much larger than the actual contents of the list.
Instead, you can write a Uint8List to the file using IOSink.add.
In the example you've provided, you could also write the entire file at once using new File(path).writeAsBytes(list).

Convert HttpPostBasicFile to Image in MVC

I get a picture by uploading and I want to convert it to image file without save it.
how can I do it?
public HttpPostedFileBase BasicPicture { get; set; }
var fileName = Path.GetFileName(BasicPicture.FileName);
// store the file inside ~/App_Data/uploads folder
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), fileName);
BasicPicture.SaveAs(path);
By this code I can save the picture on the server but I want convert it to image
like
Image img=(Image) BasicPicture;
but it doesn't work.
You could use the FromStream method:
using (Image img = Image.FromStream(BasicPicture.InputStream))
{
... do something with the image here
}
You can also convert HttpPostedFileBase to WebImage (which gives you more API - like method Resize):
public ActionResult SaveUploadedImage(HttpPostedFileBase file)
{
if(file != null)
{
var image = new System.Web.Helpers.WebImage(file.InputStream);
var path = Path.Combine(Server.MapPath("~/App_Data/uploads"), file.FileName);
image.Save(path);
}
return View();
}
With out knowing exactly what you are doing and why i can give a full intelligent answer.
Personally i would use something like this to open an image. You have saved the image to your server, so instead of casting why not new up a new image? the end result is the same!
WebImage webImage = new WebImage(path);

Need to get image filename in folder by matching if file contain certain name

In the image folder, the filename is arranged by Country_State_Date.jpg. Example : Usa_LA_4_jul.jpg. I need to get all the image filename which contain Usa. How should I go about it? Thanks
If your files are in isolated storage, you could get them with GetFileName() e.g.
using (IsolatedStorageFile f = IsolatedStorageFile.GetUserStoreForApplication())
{
f.GetFileNames("Images/USA*");
}
If they are in your project directory, then I would recommend setting the build action to 'Embedded Resource' and then you can get them by doing something along the lines of
Assembly currentAssembly = Assembly.GetExecutingAssembly();
string[] allResources = currentAssembly.GetManifestResourceNames();
string[] usaResources = allResources.Where(a => a.Contains("USA")).ToArray();
// get which ever stream you want from this collection
Stream imageStream = currentAssembly.GetManifestResourceStream(usaResources.First());
Then when you wanted to read the data from the file you just need to create a bitmap image with that stream as the image source.
var bitmapImage = new BitmapImage();
bitmapImage .SetSource(imageStream);
img.Source = bitmapImage ;

Relative path on File.ReadAllLines method

My code access a file which is in "Conf" directory inside my project directory. I am currently opening the file using absolute path like below:
File.ReadAllLines("C:\project name\Conf\filename");
I was thinikng if it's possible to use the relative path like
File.ReadAllLines("/Conf/filename");
But it's not working; as expected it throws exception. I did checked MSDN (link below) but seems "ReadAllLines()" methods doesn't accept relative path.
http://msdn.microsoft.com/en-us/library/s2tte0y1.aspx
Any idea, how can I use the relative path instead using absolute path?
Thanks,
Rahul
This is my favorite way of doing it.
Make your file an embedded resource.
/// <summary>
/// This class must be in the same folder as the embedded resource
/// </summary>
public class GetResources
{
private static readonly Type _type = typeof(GetResources);
public static string Get(string fileName)
{
using (var stream =
_type.Assembly.GetManifestResourceStream
(_type.Namespace + "." + fileName))
{
if (stream != null)
using (var reader = new StreamReader(stream))
{
return reader.ReadToEnd();
}
}
throw new FileNotFoundException(fileName);
}
}
As stated in MSDN you cannot use a relative path, however you might be able to use either Environment.CurrentDirectory or System.Reflection.Assembly.GetExecutingAssembly().Location
To make things simple, use the following:
string current_path = System.IO.Path.GetDirectoryName(Application.ExecutablePath);
string[] lines_from_file = System.IO.File.ReadAllLines(current_path + "/Conf/filename");
...additional black magic here...

Resources