Adding PImage to an ArrayList of PImage using filenames from a text file? - arraylist

So what I'm trying to do is receive the name of a text file that contains a list of filenames of a sequence of images that I have stored in a separate folder. So I get the path to the actual image files using a scanner and scan through each line of the text file, therefore reading the names of the image files in the context of their actual location. Note that the text file and folder of the images have the same path. My question is how do I get these images into my ArrayList of PImages so I can then later load and display them sequentially in a repeating loop using draw()?
private List <PImage> myImage;
private int myFrameRate, myImageNumber;
private Boolean myRunningStatus;
public AnimationPanel(String path, String textFilename) throws FileNotFoundException {
myImage = new ArrayList <PImage>();
Scanner scanner = new Scanner(new File(path + textFilename));
myFrameRate = 20;
myRunningStatus = true;
myImageNumber = 0;
while(scanner.hasNextLine()){
loadImage(path + scanner.nextLine());
myImageNumber++;
}
scanner.close();
}
public void play() {
myRunningStatus = true;
}
public void pause() {
myRunningStatus = false;
}
public void setup() {
size(300, 200);
frameRate(myFrameRate);
}
public void draw() {
background(255);
if(myRunningStatus == true){
image(myImage.get(myImageNumber), 0, 0);
}
}

I think (untested)
while(scanner.hasNextLine()){
PImage p = loadImage(path + scanner.nextLine());
myImage.add(p);
}

Related

Download the file as a zip in ASP.NET Core

I am designing an educational site. When the user downloads a training course, I want this download (training course) to be done in the form of compression (zipper), please give a solution
My code:
public Tuple<byte[],string,string> DownloadFile(long episodeId)
{
var episode=_context.CourseEpisodes.Find(episodeId);
string filepath = Path.Combine(Directory.GetCurrentDirectory(),
"wwwroot/courseFiles",
episode.FileName);
string fileName = episode.FileName;
if(episode.IsFree)
{
byte[] file = System.IO.File.ReadAllBytes(filepath);
return Tuple.Create(file, "application/force-download",fileName);
}
if(_httpContextAccessor.HttpContext.User.Identity.IsAuthenticated)
{
if(IsuserIncorse(_httpContextAccessor.HttpContext.User.Identity.Name,
episode.CourseId))
{
byte[] file = System.IO.File.ReadAllBytes(filepath);
return Tuple.Create(file, "application/force-download", fileName);
}
}
return null;
}
I write a demo to show how to download zip file from .net core:
First , Add NuGet package SharpZipLib , create an Image Folder in wwwroot and put some picture in it.
controller
public class HomeController : Controller
{
private IHostingEnvironment _IHosting;
public HomeController(IHostingEnvironment IHosting)
{
_IHosting = IHosting;
}
public IActionResult Index()
{
return View();
}
public FileResult DownLoadZip()
{
var webRoot = _IHosting.WebRootPath;
var fileName = "MyZip.zip";
var tempOutput = webRoot + "/Images/" + fileName;
using (ZipOutputStream IzipOutputStream = new ZipOutputStream(System.IO.File.Create(tempOutput)))
{
IzipOutputStream.SetLevel(9);
byte[] buffer = new byte[4096];
var imageList = new List<string>();
imageList.Add(webRoot + "/Images/1202.png");
imageList.Add(webRoot + "/Images/1data.png");
imageList.Add(webRoot + "/Images/aaa.png");
for (int i = 0; i < imageList.Count; i++)
{
ZipEntry entry = new ZipEntry(Path.GetFileName(imageList[i]));
entry.DateTime= DateTime.Now;
entry.IsUnicodeText = true;
IzipOutputStream.PutNextEntry(entry);
using (FileStream oFileStream = System.IO.File.OpenRead(imageList[i]))
{
int sourceBytes;
do
{
sourceBytes = oFileStream.Read(buffer, 0, buffer.Length);
IzipOutputStream.Write(buffer, 0, sourceBytes);
}while (sourceBytes > 0);
}
}
IzipOutputStream.Finish();
IzipOutputStream.Flush();
IzipOutputStream.Close();
}
byte[] finalResult = System.IO.File.ReadAllBytes(tempOutput);
if (System.IO.File.Exists(tempOutput)) {
System.IO.File.Delete(tempOutput);
}
if (finalResult == null || !finalResult.Any()) {
throw new Exception(String.Format("Nothing found"));
}
return File(finalResult, "application/zip", fileName);
}
}
when I click the downloadZip ,it will download a .zip file
The simple example that follows illustrates the use of the static ZipFile.CreateFromDirectory method which, despite the fact that it is in the System.IO.Compression namespace , actually resides in the System.IO.Compression.FileSystem assembly, so you need to add a reference to that in your controller.
[HttpPost]
public FileResult Download()
{
List<string> files = new List<string> { "filepath1", "filepath2" };
var archive = Server.MapPath("~/archive.zip");
var temp = Server.MapPath("~/temp");
// clear any existing archive
if (System.IO.File.Exists(archive))
{
System.IO.File.Delete(archive);
}
// empty the temp folder
Directory.EnumerateFiles(temp).ToList().ForEach(f => System.IO.File.Delete(f));
// copy the selected files to the temp folder
files.ForEach(f => System.IO.File.Copy(f, Path.Combine(temp, Path.GetFileName(f))));
// create a new archive
ZipFile.CreateFromDirectory(temp, archive);
return File(archive, "application/zip", "archive.zip");
}
Answer from Source - MikesDotNetting

Uploading byte array to MYSQL shows empty field (nothing uploaded?)

I've been trying to write a script which opens a file with UniFileViewer, sets a path to the file and passes it to various methods which serialize it and upload it to my MYSQL server. When I run the script it executes without problems but the result is 0 bytes uploaded to the database. I must have missed something here...
public class FileOpen : MonoBehaviour
{
public UITexture ProfilePic;
public static Texture2D tex = null;
public static String selectedFilePath;
void openFile()
{
UniFileBrowser.use.OpenFileWindow(OpenFile);
}
public static Texture2D LoadPNG(string selectedFilePath)
{
byte[] fileData;
fileData = File.ReadAllBytes(selectedFilePath);
tex = new Texture2D(2, 2);
tex.LoadImage(fileData); //..this will auto-resize the texture dimensions.
return tex;
}
//OPENS THE FILE AND SENDS IT TO THE SERVER
void OpenFile(string filePath)
{
selectedFilePath = filePath;
LoadPNG(selectedFilePath);
Texture2D uploadFile = tex;
byte[] bytes = uploadFile.EncodeToPNG();
string fileToSend = Convert.ToBase64String(bytes);
string[] datas = new string[1];
datas[0] = fileToSend;
LoginPro.Manager.ExecuteOnServer("SaveFile", SendToServer_Success, SendToServer_Error, datas);
}

Osmdroid - from offline folder

I am using OSMdroid to display both online and offline data in my app. The offline data are stored in a .zip file with the required structure.
Is it possible to have these offline tiles stored in a directory (extracted .zip file with the same structure)?
Could somebody please tell me how could I achive this?
Thank you.
I am sorry. I should try more before asking. But I am leaving this question here, somebody could find it useful.
Solution:
New MapTileFileProvider. I called it MapTileFileFolderProvider, it is a lightly modified MapTileFileArchiveProvider. It is using folders instead of archives. The modifications are not perfect, it is a "hot solution" that needs someone more experienced in Java/Android to make it properly.
Benefits from loading Tiles from folders:
Faster loading of tiles (I know, I won't recognize the difference).
Easier updates focused only on changed tiles not whole map plans.
Application can download tiles when is in "online mode" and then use the downloaded Tiles offline.
MapTileFileFolderProvider - only modifications
public class MapTileFileArchiveProvider extends MapTileFileStorageProviderBase
public class MapTileFileFolderProvider extends MapTileFileStorageProviderBase {
private final boolean mSpecificFoldersProvided;
private final ArrayList<String> mFolders = new ArrayList<String>();
private final AtomicReference<ITileSource> mTileSource = new AtomicReference<ITileSource>();
...
}
public MapTileFileArchiveProvider(...)
public MapTileFileFolderProvider(final IRegisterReceiver pRegisterReceiver,
final ITileSource pTileSource,
final String[] pFolders) {
super(pRegisterReceiver, NUMBER_OF_TILE_FILESYSTEM_THREADS,
TILE_FILESYSTEM_MAXIMUM_QUEUE_SIZE);
setTileSource(pTileSource);
if (pFolders == null) {
mSpecificFoldersProvided = false;
findFolders();
} else {
mSpecificFoldersProvided = true;
for (int i = pFolders.length - 1; i >= 0; i--) {
mFolders.add(pFolders[i]);
}
}
}
findArchiveFiles()
private void findFolders() {
mFolders.clear();
if (!getSdCardAvailable()) {
return;
}
String baseDirPath = Environment.getExternalStorageDirectory().toString()+"/ctu_navigator"; // TODO get from Config
File dir=new File(baseDirPath);
final File[] files = dir.listFiles();
if (files != null) {
String fileName;
for (File file : files) {
if (file.isDirectory()) {
fileName = baseDirPath + '/' + file.getName();
mFolders.add(fileName);
Utils.log(PlanTileProviderFactory.class, "Added map source: " + fileName);
}
}
}
}
#Override
protected String getName() {
return "Folders Provider";
}
#Override
protected String getThreadGroupName() {
return "folder";
}
protected class TileLoader extends MapTileModuleProviderBase.TileLoader {
#Override
public Drawable loadTile(final MapTileRequestState pState) {
ITileSource tileSource = mTileSource.get();
if (tileSource == null) {
return null;
}
final MapTile pTile = pState.getMapTile();
// if there's no sdcard then don't do anything
if (!getSdCardAvailable()) {
Utils.log("No sdcard - do nothing for tile: " + pTile);
return null;
}
InputStream inputStream = null;
try {
inputStream = getInputStream(pTile, tileSource);
if (inputStream != null) {
Utils.log("Use tile from folder: " + pTile);
final Drawable drawable = tileSource.getDrawable(inputStream);
return drawable;
}
} catch (final Throwable e) {
Utils.log("Error loading tile");
Utils.logError(getClass(), (Exception) e);
} finally {
if (inputStream != null) {
StreamUtils.closeStream(inputStream);
}
}
return null;
}
private synchronized InputStream getInputStream(final MapTile pTile, final ITileSource tileSource) {
for (final String folder : mFolders) {
final String path = folder + '/' + tileSource.getTileRelativeFilenameString(pTile);
File mapTileFile = new File(path);
InputStream in = null;
try {
in = new BufferedInputStream(new FileInputStream(mapTileFile));
} catch (IOException e) {
//Utils.log("Tile " + pTile + " not found in " + path);
}
if (in != null) {
Utils.log("Found tile " + pTile + " in " + path);
return in;
}
}
Utils.log("Tile " + pTile + " not found.");
return null;
}
}
Well, as far as I understand what you are trying to get... this is more or less what the standard XYTileSource is already doing.
So if you simply use a ready-to-use tile source like this one:
map.setTileSource(TileSourceFactory.MAPNIK);
you will see downloaded tiles files stored in /sdcard/osmdroid/tiles/Mapnik/
The main difference is that it adds a ".tile" extension at the end of each tile file (probably to prevent tools like Android gallery to index all those images).
If you have a ZIP file with tiles ready to use, you could extract them in this directory, and add .tile extension to each tile (355.png => 355.png.tile)
And TileSourceFactory.MAPNIK will be able to use them.

Wicket : FileUploadPage doesnt refresh the filepath

again, i got a problem with wicket. Im trying to upload data with my Class "FileUploadPanel", which is implemented on another Page "Class A":
Class A
...
/* uploadfields for Picture and Video */
ArrayList<String> picExt = new ArrayList<String>();
ArrayList<String> videoExt = new ArrayList<String>();
picExt.add("jpg");
videoExt.add("mp4");
final FileUploadPanel picUpload = new FileUploadPanel("picUpload", "C:\\", picExt);
final FileUploadPanel videoUpload = new FileUploadPanel("videoUpload", "C:\\", videoExt);
final Form form = new Form("form"){
protected void onSubmit() {
...
// Save the path of Video and Picture into Database
table.setVideo(videoUpload.getFilepath());
table.setPicture(picUpload.getFilepath());
...
}
...
Class FileUploadPanel
public class FileUploadPanel extends Panel {
private static final long serialVersionUID = -2059476447949908649L;
private FileUploadField fileUpload;
private String UPLOAD_FOLDER = "C:\\";
private String filepath = "";
private List<String> fileExtensions;
/**
* Constructor of this Class
* #param id the wicket-id
* #param uploadFolder the folder, in which the File will be uploaded
* #param fileExtensions List of Strings
*/
public FileUploadPanel(String id, String uploadFolder, List<String> fileExtensions) {
super(id);
this.UPLOAD_FOLDER = uploadFolder;
this.fileExtensions = fileExtensions;
add(fileUpload = new FileUploadField("fileUpload"));
}
#Override
public void onComponentTag(ComponentTag tag){
// If no file is selected on startup
if(fileUpload.getFileUpload() == null){
return;
}
final FileUpload uploadedFile = fileUpload.getFileUpload();
if (uploadedFile != null) {
// write to a new file,
File newFile = new File(UPLOAD_FOLDER
+ uploadedFile.getClientFileName());
filepath = UPLOAD_FOLDER + uploadedFile.getClientFileName();
// if file in upload-folder already exists -> delete it
if (newFile.exists()) {
newFile.delete();
}
try {
newFile.createNewFile();
uploadedFile.writeTo(newFile);
info("saved file: " + uploadedFile.getClientFileName());
} catch (Exception e) {
throw new IllegalStateException("Error");
}
}
}
public String getFilepath() {
return filepath;
}
}
Well, if i use the submit-Button on my "Class A", the Pic and Video get saved on C:\, which is quite good so far. I thought i finally get along with wicket, but i cheered too soon...
Problem: The correct path is not saved in the Database, which is handled in the Form of "Class A"
I really dont get it, because the onComponentTag(...) of my FileUploadPanel must be executed when using the submit-button. Thats because i added some validations like "picture must be a JPG or wont be saved" in onComponentTag(...) - and that worked. So im sure, the onComponentTag(...) is executed when the Submit-Button of the Form is used, which also means the filepath should be up-to-date.
What is it im doin wrong this time?
Thank in Advance!
Greeting
V1nc3nt
You are using
File newFile = new File(UPLOAD_FOLDER +
uploadedFile.getClientFileName());
this code to create a new File.
Instead of it you can try this one :
File file = new File(UPLOAD_FOLDER ,
uploadedFile.getClientFileName());
And then get the absolute path and save it:
newFile.getAbsolutePath();

excel file upload using apache file upload

I am developing an testing automation tool in linux system. I dont have write permissions for tomcat directory which is located on server. I need to develop an application where we can select an excel file so that the excel content is automatically stored in already existing table.
For this pupose i have written an form to select an file which is posted to a servlet CommonsFileUploadServlet where i am storing the uploaded file and then calling ReadExcelFile class which reads the file path and create a vector for data in file which is used to sstore data in database.
My problem is that i am not able to store the uploaded file in directory. Is it necessary to have permission rights for tomcat to do this. Can i store the file on my system and pass the path to ReadExcelFile.class
Please guide me
My code is as follows:
Form in jsp
CommonsFileUploadServlet class code:
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
out.println("<h1>Servlet File Upload Example using Commons File Upload</h1>");
DiskFileItemFactory fileItemFactory = new DiskFileItemFactory ();
fileItemFactory.setSizeThreshold(1*1024*1024);
fileItemFactory.setRepository(new File("/home/example/Documents/Project/WEB-INF/tmp"));
ServletFileUpload uploadHandler = new ServletFileUpload(fileItemFactory);
try {
List items = uploadHandler.parseRequest(request);
Iterator itr = items.iterator();
while(itr.hasNext()) {
FileItem item = (FileItem) itr.next();
if(item.isFormField()) {
out.println("File Name = "+item.getFieldName()+", Value = "+item.getString());
} else {
out.println("Field Name = "+item.getFieldName()+
", File Name = "+item.getName()+
", Content type = "+item.getContentType()+
", File Size = "+item.getSize());
File file = new File("/",item.getName());
String realPath = getServletContext().getRealPath("/")+"/"+item.getName();
item.write(file);
ReadExcelFile ref= new ReadExcelFile();
String res=ref.insertReq(realPath,"1");
}
out.close();
}
}catch(FileUploadException ex) {
log("Error encountered while parsing the request",ex);
} catch(Exception ex) {
log("Error encountered while uploading file",ex);
}
}
}
ReadExcelFile code:
public static String insertReq(String fileName,String sno) {
//Read an Excel File and Store in a Vector
Vector dataHolder=readExcelFile(fileName,sno);
//store the data to database
storeCellDataToDatabase(dataHolder);
}
public static Vector readExcelFile(String fileName,String Sno)
{
/** --Define a Vector
--Holds Vectors Of Cells
*/
Vector cellVectorHolder = new Vector();
try{
/** Creating Input Stream**/
//InputStream myInput= ReadExcelFile.class.getResourceAsStream( fileName );
FileInputStream myInput = new FileInputStream(fileName);
/** Create a POIFSFileSystem object**/
POIFSFileSystem myFileSystem = new POIFSFileSystem(myInput);
/** Create a workbook using the File System**/
HSSFWorkbook myWorkBook = new HSSFWorkbook(myFileSystem);
int s=Integer.valueOf(Sno);
/** Get the first sheet from workbook**/
HSSFSheet mySheet = myWorkBook.getSheetAt(s);
/** We now need something to iterate through the cells.**/
Iterator rowIter = mySheet.rowIterator();
while(rowIter.hasNext())
{
HSSFRow myRow = (HSSFRow) rowIter.next();
Iterator cellIter = myRow.cellIterator();
Vector cellStoreVector=new Vector();
short minColIndex = myRow.getFirstCellNum();
short maxColIndex = myRow.getLastCellNum();
for(short colIndex = minColIndex; colIndex < maxColIndex; colIndex++)
{
HSSFCell myCell = myRow.getCell(colIndex);
if(myCell == null)
{
cellStoreVector.addElement(myCell);
}
else
{
cellStoreVector.addElement(myCell);
}
}
cellVectorHolder.addElement(cellStoreVector);
}
}catch (Exception e){e.printStackTrace(); }
return cellVectorHolder;
}
private static void storeCellDataToDatabase(Vector dataHolder)
{
Connection conn;
Statement stmt;
String query;
try
{
// get connection and declare statement
int z;
for (int i=1;i<dataHolder.size(); i++)
{
z=0;
Vector cellStoreVector=(Vector)dataHolder.elementAt(i);
String []stringCellValue=new String[10];
for (int j=0; j < cellStoreVector.size();j++,z++)
{
HSSFCell myCell = (HSSFCell)cellStoreVector.elementAt(j);
if(myCell==null)
stringCellValue[z]=" ";
else
stringCellValue[z] = myCell.toString();
}
try
{
//inserting into database
}
catch(Exception error)
{
String e="Error"+error;
System.out.println(e);
}
}
stmt.close();
conn.close();
System.out.println("success");
}
catch(Exception error)
{
String e="Error"+error;
System.out.println(e);
}
}
POI will happily open from an old InputStream, it needn't be a File one.
I'd suggest you look at the Commons FileUpload Streaming API and consider just passing the excel part straight to POI without touching the disk