i am trying to access the Whatsapp folder from android internal storage but for some reason this code is not working the file path is correct but this if statement never gets true
here is the code for checking if file exixts
public static Texture2D LoadPNG()
{
Texture2D tex = null;
byte[] fileData;
if (File.Exists(filePath))
{
Debug.Log("file exists");
fileData = File.ReadAllBytes(filePath);
tex = new Texture2D(2, 2);
tex.LoadImage(fileData); //..this will auto-resize the texture dimensions.
}
return tex;
}
now filepath = "/storage/emulated/0/Whatsapp/Media/.statuses
code which makes this path
public static string GetDownloadFolder()
{
string[] temp = (Application.persistentDataPath.Replace("Android", "")).Split(new string[] { "//" }, System.StringSplitOptions.None);
filePath = temp[0]+"/WhatsApp/Media/.Statuses";
return (temp[0] + "/WhatsApp/Media/.Statuses");
}
now problem is that in android device this .statuses folder have images and video files but this if statement never gets called why i dont understand even path is correct
if (File.Exists(filePath))
{
Debug.Log("file exists");
fileData = File.ReadAllBytes(filePath);
tex = new Texture2D(2, 2);
tex.LoadImage(fileData); //..this will auto-resize the texture dimensions.
}
Your problem is that you check if file exists at folder path.
The solution is check if path is directory and get all files from it:
if (Directory.Exists(path))
{
string filenames[] = Directory.GetFiles(path);
foreach (var filename in filenames)
{
LoadPNG(filename);
}
}
Related
I have to save an image in post request in byte64String format
when i save that image i get A generic error occurred in GDI+
here is my code
byte[] ix = Convert.FromBase64String(obj.Image);
var ID = obj.Id;
using (var mStream = new MemoryStream(ix))
{
var img = Image.FromStream(mStream);
var image = obj.ImageName + ".jpg";
string path = HostingEnvironment.MapPath("/Images/" + ImageType + "/" + ID + "/" + image);
System.IO.Directory.CreateDirectory(path);
try
{
img.Save(path, System.Drawing.Imaging.ImageFormat.Jpeg);
}
catch (Exception e)
{
var d = e;
}
}
also
this is not a permission issue as i am able to create text files in the same directory
Quite simply you are confusing paths and filenames.
The problem if could hazzard a guess, you probably have a folder that is your filename, and you are trying to save a file with that same name, which windows forbids
Your code tweaked
var image = $"{obj.ImageName }.jpg";
// get the path, and only the path
string path = HostingEnvironment.MapPath($"/Images/{ImageType}/{ID}/");
// Create directory if needed (from that path)
Directory.CreateDirectory(path,image);
...
// now create the correct full path
var fullPath = Path.Combine(path,fileName);
// save
img.Save(fullPath, ImageFormat.Jpeg);
In my program, I want to save some screenshots and load them later on to compute somethings. I created a methode to compute the image names:
static public string generatePhotoName (string cameraName, float time)
{
return "G:/Data/unity/cameraDemo/" +
DataController.measurmentPath +
"/photos" + "/" +
cameraName + "/" +
time.ToString () + "_" + cameraName + ".png";
}
This worked fine for saving, but when I try to load an image, File.Exists (filePath)returns false.
But when I hardcoded the filepath, loading works fine too:
static public string generatePhotoName (string cameraName, float time)
{
return "G:/Data/unity/cameraDemo/demo/photos/Camera/test.png";
}
It even works with "real" image names(i.e. 3.827817_Camera.png).
Using Path.Combine(...) and changing "/" to "\" did not change anything...
// edit: this is my load methode
static public Texture2D loadPhotoToTexture (string filePath)
{
Texture2D tex = null;
byte[] fileData;
if (File.Exists (filePath)) {
fileData = File.ReadAllBytes (filePath);
tex = new Texture2D (2, 2);
tex.LoadImage (fileData); //..this will auto-resize the texture dimensions.
} else {
Debug.Log (filePath + " does not exist");
}
return tex;
}`
// edit2: some more code
This is how I call the methode
Texture2D photo = DataController.loadPhotoToTexture(photoData.getFileName ());
And this is my class PhotoData
public class PhotoData : BaseData
{
private string _cameraName;
public string cameraName {
get { return _cameraName; }
set { _cameraName = value; }
}
private float _time;
public float time {
get { return _time; }
set { _time = value; }
}
public PhotoData ()
{
}
public PhotoData (string cameraName, float time)
{
_cameraName = cameraName;
_time = time;
}
public string getFileName ()
{
return PlayerController.generatePhotoName (_cameraName, _time);
}
}
The problem was, that I tried to save and load the screenshots in one Update()-call.
I fixed it by changing it to right-click to take and save a screenshot and left-click to load the screenshot.
If you want to store images to a certain file on disk, not inside your game folder structure, do this: create a folder, and store its location (filepath). For example:
string screenshotFileName = time.ToString () + "_" + cameraName + ".png"
string screenshotDirectory;
screenshotDirectory = #"C:\someFolder\anotherFolder\";
try { Directory.CreateDirectory(directory); }
catch (Exception e)
{ //you should catch each exception separately
if (e is DirectoryNotFoundException || e is UnauthorizedAccessException)
Debug.LogError("OMG PANIC");
}
FileInfo filepath = new FileInfo(screenshotDirectory+screenshotFileName);
if(filepath.Exists)
{
//load the file
}
You could also simply create a folder, with a relative path, which will be in the same folder as your executable, by changing the screenshotDirectory to
screenshotDirectory = #"screenshots\"+cameraName+#"\";
Edit:
You seem to load the texture correctly. Are you assigning it to the material's main texture? Where is your code encountering the problem? For example if you're running this script on the same object that you want the texture to be applied:
this.GetComponent<Renderer>().material.mainTexture = loadedTexture;
Also, when you want to load images, it's best that you use the Resources folder, which uses forwards slashes, not . Store everything that you might want to load on runtime there, and use Resources.Load().
I am trying to create a Windows app which uploads files to FTP. Essentially, it looks for .jpeg files in a given folder, it reads through the barcodes found in the .jpg files before uploading it into the FTP server, and entering the URL into the database for our records.
As there will be multiple files at any given time in the folder, I am essentially trying to read them in a loop, and process them accordingly. However, I get an OutOfMemoryException whenever the loop starts again. I am trying to figure out what I'm doing wrong here. I have appended my code below:
private void btnProcess_Click(object sender, RoutedEventArgs e)
{
podPath = Directory.GetFiles(DestPath, "*.jpg");
List<string> scans = new List<string>(podPath.Length);
List<string> badscans = new List<string>();
byte[] imageBytes;
string filename, result;
POD conpod = new POD();
OTPOD otpod = new OTPOD();
ConsignmentObj scanJob;
//Pickup OTScan;
//Consolidate ccv;
for (int i = 0; i < podPath.Count(); i++ )
{
filename = podPath[i].ToString();
using (Bitmap bm = (Bitmap)Bitmap.FromFile(filename))
{
var results = barcodeReader.Decode(bm);
result = results.ToString();
bm.Dispose();
}
if (result != null)
{
//if barcode can be read, we throw the value into the database to pull out relevant information
if (result.Contains(ConNotePrefix))
{
#region Consignments
scanJob = getCon(result.ToString());
final = ImageFolder + "\\" + result.ToString() + ".jpg";
using (System.Drawing.Image img = System.Drawing.Image.FromFile(filename))
{
MemoryStream ms = new MemoryStream();
try
{
img.Save(ms, ImageFormat.Jpeg);
imageBytes = ms.ToArray();
img.Dispose();
}
finally
{
ms.Flush();
ms.Close();
ms.Dispose();
}
}
lock (filename)
{
if (System.IO.File.Exists(filename))
{
File.Delete(filename);
}
}
using (var stream = File.Create(final)) { }
File.WriteAllBytes(final, imageBytes);
File.Delete(filename);
conpod.ConsignmentID = scanJob.ConsignmentID;
conpod.UserID = 1;
conpod.Location = ftpUrl + "//" + result.ToString() + ".jpg";
conpod.rowguid = Guid.NewGuid();
UploadFilesToFtp(ftpUrl, ftpUser, ftpPass, final, result.ToString() + ".jpg");
insertPOD(conpod);
scans.Add(result.ToString());
#endregion
}
}
else
{
badscans.Add(filename);
}
}
this.lbScans.ItemsSource = scans;
this.lbBadScans.ItemsSource = badscans;
}
The FTP method, UploadFilesToFtp(x, x, x, x, x, x) is not a problem here. All feedback will be much appreciated.
An OutOfMemoryException can also be thrown by the method FromFile of the Image class when
The file does not have a valid image format.
or
GDI+ does not support the pixel format of the file.
So i think there is a problem with one of your image files you are reading. One solution is to catch the OutOfMemoryException and adding the file to the badscans.
try{
using (Bitmap bm = (Bitmap)Bitmap.FromFile(filename)) {
var results = barcodeReader.Decode(bm);
result = results.ToString();
bm.Dispose();
}
}
catch(OutOfMemoryException) {
badscans.add(filename);
}
Below is some code that
creates a directory
uses MagickNet to covert a PDF into separate BMP images and stores it in a folder (ImagePath)
Then it uses TessNet2 to scan each image in that folder to parse out information
I can't seem to get the foreach loop that scans the ImagePath folder. Any help?
The error right now is on the 'foreach' statement and it says "Cannot convert type 'char' to 'System.Drawing.Image'"
static void Main(string[] args)
{
string ImagePath = exePath + "\\Images";
if (!Directory.Exists(ImagePath))
{
Directory.CreateDirectory(ImagePath);
}
MagickReadSettings settings = new MagickReadSettings();
settings.Density = new MagickGeometry(300, 300);
using (MagickImageCollection images = new MagickImageCollection())
{
images.Read(#"D:\Test\ABStest.pdf",settings);
int page = 1;
foreach (MagickImage image in images)
{
image.Write(ImagePath + "\\ABS" + page + ".bmp");
page++;
}
}
foreach (Image item in ImagePath)
{
using (Bitmap bmp = new Bitmap(item))
{
tessnet2.Tesseract tessocr = new tessnet2.Tesseract();
tessocr.Init(#"C:\Users\Matt Taylor\Documents\Visual Studio 2012\Projects\TessNet2\TessNet2\bin\Debug\tessdata", "eng", false);
tessocr.GetThresholdedImage(bmp, Rectangle.Empty).Save("c:\\temp\\" + Guid.NewGuid().ToString() + ".bmp");
// Tessdata directory must be in the directory than this exe
Console.WriteLine("Multithread version");
ocr.DoOCRMultiThred(bmp, "eng");
//Console.WriteLine("Normal version");
//ocr.DoOCRNormal(bmp, "eng");
}
}
}
You can use Directory.GetFiles to return all the filenames in the directory and create your Bitmaps from there
foreach (string imageFileName in Directory.GetFiles(ImagePath))
{
using (Bitmap bmp = new Bitmap(imageFileName))
{
}
}
But if there are other files in that folder you should add a filter
foreach (string imageFileName in Directory.GetFiles(ImagePath, "*.jpg"))
{
using (Bitmap bmp = new Bitmap(imageFileName))
{
}
}
You don't need to save the file to disk. You could use the .ToBitmap() method of MagickImage.
foreach (MagickImage image in images)
{
using (Bitmap bmp = image.ToBitmap())
{
tessnet2.Tesseract tessocr = new tessnet2.Tesseract();
// etc...
}
}
You are looping through String ImagePath, which gives you a collection of characters. You need to search through the directory with Directory.GetFiles(), and load the images with Image.FromFile():
foreach (String itemPath in Directory.GetFiles(ImagePath))
{
using (Image item = Image.FromFile(itemPath))
{
...
}
}
I am trying to create a action, in a mvc project. that can upload files and images to my azure storage. but for some reason will it just not upload corrently, that is what i am guessing.
If i upload the image with "Azure Storage Explorere" dose it work fine.
Example: http://storage.sogaard.us/company1/wallpaper-396234.jpg
But if i try to upload the image though my action will it not work, it send a 200 for succes and the right conten type, but the image will not load, and my developer tool tells me i got not data from the server.
Example: http://storage.sogaard.us/company1/b9206edac188e1d8aa2b3be7cdc4b94a.jpg
I have tried to save the uploaded til to my local computer instead of the azure storage and it worked fine there! I can simply not find the reason and this have been bugging me all day :(
Here is my code
[HttpPost]
public ActionResult Upload(FilesUploadModel model, IEnumerable<HttpPostedFileBase> files)
{
if(ModelState.IsValid)
{
if (files != null && files.Any())
{
int maxSizeInBytes = ConfigurationManager.Instance.Configuration.FileMaxSize;
Size thumbSize = new Size(200, 200);
foreach (HttpPostedFileBase file in files.Where(x => x != null))
{
CMS.Common.Data.File _file = new Sogaard.Inc.CMS.Common.Data.File();
// is any files uploadet?
if (!(file.ContentLength > 0))
{
FlashHelper.Add(Text("File not received"), FlashType.Error);
continue;
}
// is the file larger then allowed
if (file.ContentLength > maxSizeInBytes)
{
FlashHelper.Add(Text("The file {0}'s file size was larger then allowed", file.FileName), FlashType.Error);
continue;
}
var fileName = Encrypting.MD5(Path.GetFileNameWithoutExtension(file.FileName) + DateTime.Now) + Path.GetExtension(file.FileName);
string mimeType = FileHelper.MimeType(FileHelper.GetMimeFromFile(file.InputStream));
_file.SiteId = SiteId();
_file.Container = GetContainerName();
_file.FileName = Path.GetFileName(file.FileName);
_file.FileNameServer = fileName;
_file.Created = DateTime.Now;
_file.Folder = model.Folder;
_file.Size = file.ContentLength;
_file.Type = mimeType;
if (mimeType.ToLower().StartsWith("image/"))
{
try
{
// So we don't lock the file
using (Bitmap bitmap = new Bitmap(file.InputStream))
{
_file.Information = bitmap.Width + "|" + bitmap.Height;
if (bitmap.Height > 500 && bitmap.Width > 500)
{
var thumbfileName = Encrypting.MD5(Path.GetFileNameWithoutExtension(file.FileName) + "thumb" + DateTime.Now) + ".jpeg";
Size thumbSizeNew = BaseHelper.ResizeImage(bitmap.Size, thumbSize);
Bitmap thumbnail = (Bitmap)bitmap.GetThumbnailImage(thumbSizeNew.Width,
thumbSizeNew.Height,
ThumbnailCallback,
IntPtr.Zero);
_file.ThumbFileNameServer = thumbfileName;
// Retrieve reference to a blob named "myblob"
CloudBlob blob = container().GetBlobReference(_file.ThumbFileNameServer);
blob.Metadata["Filename"] = Path.GetFileNameWithoutExtension(file.FileName) + "-thumb" + ".jpg";
blob.Properties.ContentType = "image/jpeg";
// Create or overwrite the "myblob" blob with contents from a local file
using (MemoryStream memStream = new MemoryStream())
{
thumbnail.Save(memStream, ImageFormat.Jpeg);
blob.UploadFromStream(memStream);
}
blob.SetMetadata();
blob.SetProperties();
}
}
}
catch (Exception e)
{
if (e.GetType() != typeof (DataException))
FlashHelper.Add(Text("The image {0} was not a valid image", file.FileName),
FlashType.Error);
// Removing the file
System.IO.File.Delete(file.FileName);
}
}
else
{
_file.Information = null;
}
// Retrieve reference to a blob named "myblob"
CloudBlob blobF = container().GetBlobReference(fileName);
blobF.Metadata["Filename"] = file.FileName;
blobF.Properties.ContentType = mimeType;
// Create or overwrite the "myblob" blob with contents from a local file
blobF.UploadFromStream(file.InputStream);
blobF.SetMetadata();
blobF.SetProperties();
fileService.Save(_file);
}
}
return RedirectToAction("Display", new { Folder = model.Folder });
}
model.FolderSugestion = fileService.GetFolders(SiteId());
return View(model);
}
private CloudBlobContainer container()
{
// Retrieve storage account from connection-string
CloudStorageAccount storageAccount = CloudStorageAccount.Parse(
RoleEnvironment.GetConfigurationSettingValue("StorageConnectionString"));
// Create the blob client
CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
// Retrieve reference to a previously created container
var container = blobClient.GetContainerReference(GetContainerName());
container.CreateIfNotExist();
return container;
}
private string GetContainerName()
{
return "company" + SiteId();
}
In the thumbnail code path, I think you need memStream.Position = 0 to reset the stream back to the beginning before trying to upload it.
For the other (non-image) code path, nothing stands out as wrong. Does that code work?
In both code paths, you don't need blob.SetMetadata() and blob.SetProperties(), since those will be done when the upload happens.
[EDIT] Also, what does GetMimeFromFile do? Does it read from the stream (thus perhaps leaving the stream position somewhere other than the beginning)?