Reload EditorPane - java

I found here: what I was searching for but still I have some issues.
This is my action code:
private void jMenuItem1ActionPerformed(java.awt.event.ActionEvent evt) throws IOException {
jEditorPane1.setContentType("text/html");
int returnVal = FileChooser1.showOpenDialog(this);
if (returnVal == FileChooser1.APPROVE_OPTION) {
String image = String.format("<img src=\"%s\">", FileChooser1.getSelectedFile());
jEditorPane1.setText(image);
}
}
Here is a screenshot of what happens, as you can see the image is not loaded.
http://postimg.org/image/agc665ih1/
But if I save the file (with save button) and reopen the same file (with open button), the image is there and is perfectly loaded.
I already tried the .repaint() and .revalidate() methods, but is not working..
Any idea?

This may be problem in setting up path in JEditorPane page. use this:
String image = String.format("<img src=\"%s\">", FileChooser1.getSelectedFile().getPath());
I am assuming that you have already selected appropriate editorKit for JEditorPane.

So now I can answer with my code. I am using this class for the file chooser:
import java.io.File;
import javax.swing.filechooser.FileFilter;
class jpgfilter extends FileFilter {
public boolean accept(File file) {
return file.isDirectory() || file.getAbsolutePath().endsWith(".jpg");
}
public String getDescription() {
return "JPG image (*.jpg)";
}
}
And in my main class I have this:
FileChooser1 = new javax.swing.JFileChooser();
FileChooser1.setDialogTitle("Choose your image:");
FileChooser1.setFileFilter(new jpgfilter());
And that's it.

So I actually found some kind of a solution but I think there is really too much code and that I should do it easily..I actually insert the image and simultaneously save and open the content of the EditorPane as .html file.
The code:
jEditorPane1.setContentType("text/html");
int returnVal = FileChooser1.showOpenDialog(this);
if (returnVal == FileChooser1.APPROVE_OPTION) {
String image = String.format("<img src=\"%s\">", FileChooser1
.getSelectedFile().getPath());
jEditorPane1.setText(image);
String type = jEditorPane1.getContentType();
OutputStream os = new BufferedOutputStream(new FileOutputStream(
"/Library/java_test/temp" + ".html"));
Document doc = jEditorPane1.getDocument();
int length = doc.getLength();
if (type.endsWith("/rtf")) {
// Saving RTF - use the OutputStream
try {
jEditorPane1.getEditorKit().write(os, doc, 0, length);
os.close();
} catch (BadLocationException ex) {
}
} else {
// Not RTF - use a Writer.
Writer w = new OutputStreamWriter(os);
jEditorPane1.write(w);
w.close();
}
String url = "file:///" + "/Library/java_test/temp" + ".html";
jEditorPane1.setPage(url);
}

Related

How to properly save frames from mp4 as png files using ExtractMpegFrames.java?

I am trying to get all frames from an mp4 file using the ExtractMpegFrames.java class found here http://bigflake.com/mediacodec/ExtractMpegFramesTest.java.txt
What I currently do is create a temp file (File.createTempFile) in a directory that stores all the frames, create a FileOutputStream and do
bm.compress(Bitmap.CompressFormat.PNG, 100, fOut)
where fOut is the OutputStream with the file.
Currently, the saved images look like this: https://imgur.com/a/XpsV2
Using the Camera2 Api, I record a video and save it as an mp4. According to VLC, the color space for the video is Planar 4:2:0 YUV Full Scale.
Looking around, it seems that each vendor uses different color spaces
https://stackoverflow.com/a/21266510/7351748. I know ffmpeg can conversions with color spaces, but I cannot use it.
I am not sure where to start to solve this issue of the strange output pngs. I am assuming that this is a color space issue, but I can be completely wrong here.
You can get all Frames of Video Using ffmpeg library here is working code.
add dependancy
compile 'com.writingminds:FFmpegAndroid:0.3.2'
to your gradle
private void loadFFMpegBinary() {
try {
if (ffmpeg == null) {
ffmpeg = FFmpeg.getInstance(this);
}
ffmpeg.loadBinary(new LoadBinaryResponseHandler() {
// #Override
// public void onFailure() {
// showUnsupportedExceptionDialog();
// }
#Override
public void onSuccess() {
Log.d(TAG, "ffmpeg : correct Loaded");
}
});
} catch (FFmpegNotSupportedException e) {
} catch (Exception e) {
Log.d(TAG, "EXception : " + e);
}
}
here is image extratct method
public void extractImagesVideo() {
File moviesDir = Environment.getExternalStoragePublicDirectory(
Environment.DIRECTORY_PICTURES
);
String filePrefix = "extract_picture";
String fileExtn = ".jpg";
String yourRealPath = getPath(Pick_Video.this, DataModel.selectedVideoUri);
Log.d("selected url", "" + DataModel.selectedVideoUri);
File src = new File(yourRealPath).getAbsoluteFile();
File appDir=new File(moviesDir,"/"+app_name+"/");
if(!appDir.exists())
appDir.mkdir();
DataModel.appDir=appDir;
File dir = new File(appDir, "testVideo");
int fileNo = 0;
while (dir.exists()) {
fileNo++;
dir = new File(moviesDir+"/"+app_name+"/", "testVideo" + fileNo);
}
dir.mkdir();
DataModel.dir = dir;
resultList = new ArrayList<String>(256);
filePath = dir.getAbsolutePath();
File dest = new File(dir, filePrefix + "%03d" + fileExtn);
Log.d(TAG, "startTrim: src: " + src.toString());
Log.d(TAG, "startTrim: dest: " + dest.getAbsolutePath());
String[] complexCommand = { "-i",""+src.toString(),"-qscale:v", "2","-vf", "fps=fps=20/1",dest.getAbsolutePath()};
//"-qscale:v", "2","-vf", "fps=fps=20/1",//
//works fine with speed and
execFFmpegBinary(complexCommand);
}
call this two method on button click event
Comment If Any query.

Adding a String to a file name and still be able to use it

I have a xml file that I'm getting its full path, and pass it to a function where I add a String to its name. However I'm not being able to use it (the initial fullpath) after adding the string. How can it be done, that after getting the fullpath in search(String dirName), and adding the string in lk(String fullpath), I can still use the path which is returned by search(String dirName).
public String search( String dirName)throws Exception{
String fullPath = null;
File dir = new File(dirName);
if ( dir.isDirectory() )
{
String[] list = dir.list(new FilenameFilter()
{
#Override
public boolean accept(File f, String s )
{
return s.endsWith(".xml");
}
});
if ( list.length > 0 )
{
fullPath = dirName+list[0];
lockFile(fullPath);
return fullPath;
}
}
return "";
}
public void lk( String fullPath) throws Exception {
File f = new File(fullPath);
String fileNameWithExt = f.getName();
try {
File newfile =new File(fileNameWithExt+".lock");
if(f.renameTo(newfile)){
System.out.println("Rename succesful");
}else{
System.out.println("Rename failed");
}
} catch (Exception e) {
e.printStackTrace();
}
}
try this
File originalFile = new File(<file parent path>, "myxmlfile");
File cloneFile = new File(originalFile.getParent(),
originalFile.getName()+"<anything_i_want_to_add>");
Files.copy(originalFile.toPath(),cloneFile.toPath());
//now your new file exist and you can use it
originalFile.delete();//you delete the original file
...
//after you are done with everything and you want the path back
Files.copy(cloneFile.toPath(),originalFile.toPath());
cloneFile.delete();
In your lock method, you are calling renameTo method. Because of that, the original filename is now gone, and is replaced by the new filename that ends with .lock.
The java.io.File class is not a file pointer but an object to hold a filename. Using a file object that still refers to an old filename will cause an error.
To answer your question: If you want the old filename after locking, you must use a different approach in locking your file. For example, MS Access locks their .accdb files by creating a lockfile with the same filename as the opened .accdb file.
You may use this code as a reference:
public boolean fileIsLocked(File file) {
File lock = new File(file.getAbsolutePath() + ".lock");
return lock.exists();
}
public void lockFile(File file) {
if (!fileIsLocked(file)) {
File lock = new File(file.getAbsolutePath() + ".lock");
lock.createNewFile();
lock.deleteOnExit(); // unlocks file on JVM exit
}
}
public void unlockFile(File file) {
if (fileIsLocked(file)) {
File lock = new File(file.getAbsolutePath() + ".lock");
lock.delete();
}
}

Write String into a file, which the user chooses from <input type="file">

I want to write a String to a file, which the user chooses from . I'm unable to do it because I need the fileName and fileLocation to write my String to the file. But the request.getParamater("") gives me just the fileName. I know that it won't return the fileLocation because of security issues. Then, how do I write my String from the file chosen on my jsp. Please advise.
You cannot write to that file directly.
Short answer : Make a copy file on server.
Long answer:
1) Get the file.
2) Save it on server.
3) Append to that file. Do not overwrite.
4) Again send back the file to user with response.
Do some steps
Get file name using getFileName() method. Store it on server side
if some one wants to Save Same file name again then you append Some Date after file Name. so you can easily get all the files without any code changes.
After write String into file close the file and flush .
See i have upload the file form Front End and Store it on Some local system . when you try to upload Same file again then it append Date with File name
public class uploadFile {
private File myFile;
private String myFileContentType;
private String myFileFileName;
private String destPath;
public String upload() throws IOException {
try {
destPath = System.getProperty("user.home") + System.getProperty("file.separator") + "File-Uploads";
File destFile = new File(destPath, myFileFileName);
File file1 = new File(destFile.toString());
boolean b = false;
Date date = new Date();
if (!(file1.exists())) {
b = file1.createNewFile();
}
if (b) {
FileUtils.copyFile(myFile, destFile);
} else {
String fileContent = "";
File f = new File(file1.toString());
FileInputStream inp = new FileInputStream(f);
byte[] bf = new byte[(int) f.length()];
inp.read(bf);
fileContent = new String(bf, "UTF-8");
System.out.println("file===>" + fileContent);
String filename = destFile.toString() + date;
FileWriter fw = new FileWriter(filename, true);
fw.write(fileContent);
fw.close();
FileUtils.copyFile(myFile, destFile);
}
return SUCCESS;
} catch (IOException e) {
return SUCCESS;
}
}
public File getMyFile() {
return myFile;
}
public void setMyFile(File myFile) {
this.myFile = myFile;
}
public String getMyFileContentType() {
return myFileContentType;
}
public void setMyFileContentType(String myFileContentType) {
this.myFileContentType = myFileContentType;
}
public String getMyFileFileName() {
return myFileFileName;
}
public void setMyFileFileName(String myFileFileName) {
this.myFileFileName = myFileFileName;
}
}

Play! 2 with Java on heroku, save file temporary

At the very begining - sorry for my english.
I'm developing a play-application in java and deploy it to heroku.
I like to create a picture (a QRCode to be precisely), store it temporary and display it on the next page.
I do know about herokus ephemeral filesystem, but if I understand right, on the cedar stack, I am able to create files wherever I like, as long as it's ok, that they won't be stored for a long time. The app just needs to generate a QR, I scan it and the file may be deleted.
It seems as if the file is not created. Any ideas of how I can manage to temporary save and show my QRs?
Controller
public class Application extends Controller {
private static String workingDirectory = "public/images/";
public static Result qrCode() {
String msg = "I am a QR-String";
BufferedImage image = (BufferedImage) QR.stringToImage(msg);
String imgPath = workingDirectory+"posQR.png";
try{
File outputfile = new File(imgPath);
ImageIO.write(image,"png",outputfile);
}catch(IOException e){
e.printStackTrace();
}
return ok(views.html.qrCode.render());
}
}
View qrCode
<img src="#routes.Assets.at("images/posQR.png")">
Edit 1
Stored the image as tempFile an pass it to the view.
On heroku an local the view contains the exact absolute path, but the image won't load.
Any ideas left?
Controller
public class Application extends Controller {
private static String workingDirectory = "public/images/";
public static Result qrCode() {
String msg = "I am a QR-String";
BufferedImage image = (BufferedImage) QR.stringToImage(msg);
File outputfile = null;
String imgPath = workingDirectory+"posQR.png";
try{
outputfile = File.createTempFile("posQR",".png");
ImageIO.write(image,"png",outputfile);
}catch(IOException e){
e.printStackTrace();
}
return ok(views.html.qrCode.render(outputfile.getAbsolutePath()));
}
View qrCode
#(qrPath: String)
...
<img id="qr" src=#qrPath>
Does workingDirectory end with file separator?
String imgPath = workingDirectory+"posQR.png";
This helped me: Play! framework 2.0: How to display multiple image?
Finaly I did it. The trick was not to do src=path but src=getImage(path). Still strange, but now it works.
routes
GET /tmp/*filepath controllers.Application.getImage(filepath: String)
Application
public class Application extends Controller {
public static Result qrCode() {
String msg = "I am a QR-String";
BufferedImage image = (BufferedImage) QR.stringToImage(msg);
File outputfile = null;
try{
outputfile = File.createTempFile("posQR",".png");
ImageIO.write(image,"png",outputfile);
}catch(IOException e){
e.printStackTrace();
}
return ok(views.html.qrCode.render(outputfile.getAbsolutePath()));
}
...
public static Result getImage(String imgPath){
return ok(new File(imgPath));
}
}
view qrCode
#(qrPath: String)
...
<img src="#routes.Application.getImage(qrPath)"/>
Thanks for your help :D

Is it possible to select multiple directories at once with JFileChooser

As the title states, is there a way to select multiple directories at once (all sub-directories immediately within a primary directory) with JFileChooser so I don't have to re-open the file chooser window for each directory?
Once again I've solved my own question after asking it.
The thing that was preventing me from getting it to work previously was I was using the check for multi-select rather than the set for multi-select, and apparently was using that wrong as well as I kept getting an error. Anyway, the working version is below:
class AddDirectory implements ActionListener {
public void actionPerformed(ActionEvent ae) {
File[] theDir = null;
theDir = selectDir();
if(theDir != null) {
for(File z : theDir) {
String[] curRow = { z.toString(), "Waiting"};
dlm.addRow(curRow);
}
}
return;
}
private File[] selectDir() {
JFileChooser fileChooser = new JFileChooser(lastDir);
fileChooser.setMultiSelectionEnabled(true);
fileChooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
int showOpenDialog = fileChooser.showOpenDialog(null);
if (showOpenDialog != JFileChooser.APPROVE_OPTION) {
return null;
}
File[] uploadDir = fileChooser.getSelectedFiles();
lastDir = new File(uploadDir[uploadDir.length-1].getParent());
return uploadDir;
}
}
Once I get the directories, they're loaded into a JTable to be modified before running the rest of my code on them.

Categories