Problems creating a icon - java

I have problems trying to create an ImageIcon for my project. My createImageIcon method goes as follows ::
protected ImageIcon createImageIcon(String path, String description)
{
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null)
{
return new ImageIcon(imgURL, description);
}
else
{
System.err.println("Couldn't find file: " + path);
return null;
}
}
And the line that creates the Icon ::
ImageIcon icon = createImageIcon("**ICON URL***","Java");
Unfortunately, I cannot create any Icon because all the URLs I enter are not found (the file is not found). Could someone please tell me how to get the URL of an image found online that will work and will fit for this method? Thanks.

Related

change part of the screen javaFX

so Basically I an working on this project car registration and I find difficulties in changing part of the page so I used the boarder pane to and I reached a point that I can change the middle pane but to null I believe that the problem comes from here
This is my code:
private Pane view;
#FXML
public Pane getPage(String fileName) {
try {
URL fileUrl = App.class.getResource("/org.example/" + fileName + ".fxml");
if (fileUrl == null) {
throw new java.io.FileNotFoundException("FXML file can't be found");
}
view = new FXMLLoader().load(fileUrl);
} catch (Exception e){
System.out.println("No page " + fileName + " please check FxmlLoader.");
}
return view;
}
This is where I believe the problem comes from:
URL fileUrl = App.class.getResource("/org.example/" + fileName + ".fxml");
because I get (No page addingACar.fxml please check FxmlLoader.
)
my question is I am not sure how to reach the file I assigned as a URL

How to POST File to an URL in Java CodeName One?

I wanna to upload an image in java and copied in a directory with WebService in Symfony
i tried it with Postman and it worked but when i did it in Java, it didn't work, i don't know how to pass a file like paramatre in the Url request
Please help me to find a solution
Symfony Code:
$file = $request->files->get('nomImage');
$status = array('status' => "success","fileUploaded" => false);
// If a file was uploaded
if(!is_null($file)){
// generate a random name for the file but keep the extension
$filename = uniqid().".".$file->getClientOriginalExtension();
$path = "C:\wamp64\www\pidev\web\uploads\images";
$file->move($path,$filename); // move the file to a path
$status = array('status' => "success","fileUploaded" => true);
}
return new JsonResponse($status);
Postman Screenshot:
I sent the URL with Postman and add the image in Body with nomImage like key and the image like value and it worked
Java Code:
This code is to connect to the URL and i wanted to get the image like file in the URL like in Postman
public void ajoutProduit(File image)
{
ConnectionRequest con = new ConnectionRequest();
con.setUrl("http://localhost/PIDEV/web/app_dev.php/Api/produit/ajout?nomImage="+image);
NetworkManager.getInstance().addToQueueAndWait(con);
}
This is my form and the uploading of the image and execute the Copy of the image which it didn't work
public class AjoutProduit {
private Form fAjout = new Form("", new BoxLayout(BoxLayout.Y_AXIS));
public AjoutProduit() {
TextField nomProduit = new TextField("", "Nom du produit");
TextField descProduit = new TextField("", "Description du produit");
ComboBox<String> opProduit = new ComboBox<>(
"",
"echanger",
"donner",
"recycler",
"reparer"
);
final String[] jobPic = new String[1];
Label jobIcon = new Label();
Button image = new Button("Ajouter une image ");
final String[] image_name = {""};
final String[] pathToBeStored={""};
/////////////////////Upload Image
image.addActionListener((ActionEvent actionEvent) -> {
Display.getInstance().openGallery(new ActionListener() {
#Override
public void actionPerformed(ActionEvent ev) {
if (ev != null && ev.getSource() != null) {
String filePath = (String) ev.getSource();
int fileNameIndex = filePath.lastIndexOf("/") + 1;
String fileName = filePath.substring(fileNameIndex);
Image img = null;
try {
img = Image.createImage(FileSystemStorage.getInstance().openInputStream(filePath));
} catch (IOException e) {
e.printStackTrace();
}
image_name[0] = System.currentTimeMillis() + ".jpg";
jobIcon.setIcon(img);
System.out.println(filePath);
System.out.println(image_name[0]);
try {
pathToBeStored[0] = FileSystemStorage.getInstance().getAppHomePath()+ image_name[0];
OutputStream os = FileSystemStorage.getInstance().openOutputStream(pathToBeStored[0]);
ImageIO.getImageIO().save(img, os, ImageIO.FORMAT_JPEG, 0.9f);
os.close();
}
catch (Exception e) {
e.printStackTrace();
}
}
}
}, Display.GALLERY_IMAGE);});
////////////Copied with URL Symfony
Button myButton = new Button("Valider");
myButton.addActionListener(new ActionListener() {
#Override
public void actionPerformed(ActionEvent actionEvent) {
ServiceProduit sp = new ServiceProduit();
ServiceEchange se = new ServiceEchange();
String path = "C:/Users/omark/.cn1/"+image_name[0];
File file = new File(path);
sp.ajoutProduit(file);
}
});
fAjout.addAll(nomProduit,descProduit,opProduit,jobIcon,myButton,image);
fAjout.show();
}
Try the x-www-url-form-encoded. If that works then use MultipartRequest to submit binary data to the server. It implicitly handles form encode submission for you. If something doesn't work use the network monitor tool in Codename One to inspect the outgoing request/response which often provide helpful information about the process.
This isn't correct:
ConnectionRequest con = new ConnectionRequest();
con.setUrl("http://localhost/PIDEV/web/app_dev.php/Api/produit/ajout?nomImage="+image);
NetworkManager.getInstance().addToQueueAndWait(con);
You're submitting a URL using the GET style argument passing. You need to submit the date of the image and not the image itself. You need to use addArgument() or addData() etc. to include the content in the request.
i resolved the problem, i modified the " Java Code ":
MultipartRequest cr = new MultipartRequest();
cr.setUrl("http://localhost/PIDEV/web/app_dev.php/Api/produit/ajout");
cr.setPost(true);
String mime = "image/png";
try {
cr.addData("file", filePath, mime);
} catch (IOException e) {
e.printStackTrace();
}
String fichernom = System.currentTimeMillis() + ".png";
cr.setFilename("file", fichernom);
InfiniteProgress prog = new InfiniteProgress();
Dialog dlg = prog.showInifiniteBlocking();
cr.setDisposeOnCompletion(dlg);
NetworkManager.getInstance().addToQueueAndWait(cr);

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.

How to create an instance of ImageIcon

I'm trying to create an instance of ImageIcon according to the instructions here (http://docs.oracle.com/javase/tutorial/uiswing/components/icon.html)
/** Returns an ImageIcon, or null if the path was invalid. */
protected ImageIcon createImageIcon(String path,
String description) {
java.net.URL imgURL = getClass().getResource(path);
if (imgURL != null) {
return new ImageIcon(imgURL, description);
} else {
System.err.println("Couldn't find file: " + path);
return null;
}
}
I have the image in the same folder as the java class, but it returns "Couldn't find file: .....". What should I do?
Class.getResource() is for accessing stuff via classloader, e.g. things in the same jar as your application.
To access a file from filesystem create URL from file, e.g. new File(path).toURI().toURL();

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

Categories