I hava this piece of code:
import com.xuggle.mediatool.IMediaWriter;
import com.xuggle.mediatool.ToolFactory;
import com.xuggle.xuggler.ICodec;
public class ImageToVideo implements Runnable {
private static Dimension dimension;
private final IMediaWriter writer;
long startTime;
LoadFrame loadframe;
public ImageToVideo(int framespersecond, LoadFrame loadframe) {
this.loadframe = loadframe;
writer = ToolFactory.makeWriter(Project.getInstance().getFileURLStr() + Project.getInstance().getProjectName() + ".mp4");
dimension = Toolkit.getDefaultToolkit().getScreenSize();
writer.addVideoStream(0, 0, ICodec.ID.CODEC_ID_MPEG4, dimension.width / 2, dimension.height / 2);
startTime = System.nanoTime();
}
#Override
public void run() {
Project project = Project.getInstance();
for (int index = 0; index <= project.getTimeLineImageCount(); index++) {
loadframe.updateProgress(index/project.getTimeLineImageCount());
ImageIcon imgtoencode = (ImageIcon)project.getNextTimeLineImage();
BufferedImage imgtoencodebuf = (BufferedImage)imgtoencode.getImage();
writer.encodeVideo(0, imgtoencodebuf, System.nanoTime() - startTime, TimeUnit.NANOSECONDS);
}
project.setWalkIndexes();
writer.close();
}
}
Wich should be converting a list of images to a video. But when I try to run it I get this error:
Exception in thread "AWT-EventQueue-0" java.lang.NoClassDefFoundError: org/slf4j/LoggerFactory
at com.xuggle.ferry.JNIMemoryManager.<init>(JNIMemoryManager.java:861)
at com.xuggle.ferry.JNIMemoryManager.<clinit>(JNIMemoryManager.java:860)
at com.xuggle.mediatool.MediaWriter.<clinit>(MediaWriter.java:119)
at com.xuggle.mediatool.ToolFactory.makeWriter(ToolFactory.java:149)
at Operations.ImageToVideo.<init>(ImageToVideo.java:31)
at GUI.MainScreen.actionPerformed(MainScreen.java:501)
etc. I got the code from an example on internet:http://examples.javacodegeeks.com/desktop-java/xuggler/create-video-from-image-frames-with-xuggler/"
I am really new to Xuggle, I hope someone can help me out here. Thanks
You are missing the sl4j library Xuggle will not work without that
Download library from here --> http://www.slf4j.org/download.html and add the jar's to your project library (class path)
Related
I am developing an application in android in which i want to print the Image on reciept using thermal printer.
To achive this task i have added the escpos-coffee package in my application.
To print image it is using
import java.imageio.BufferedImage, to read image it is using ImageIO.read(file) method both classes are located in rt.jar library which i have externally added in the project.
But when i try to build it, it thorws error :
Error: MethodHandle.invoke and MethodHandle.invokeExact are only
supported starting with Android O (--min-api 26)
Before that my sdk version versions were changed, then changed the min sdk to 5.1 and (target & compile skd version to 7.0) then it started throwing.
Any help in detail will be appreciated.
Thank you.
you need to use SNAPSHOT version com.github.anastaciocintra:escpos-coffee:4.0.0-SNAPSHOT
(SNAPSHOT yet...)
and, after that, implement CoffeImage interface:
(CoffeeImageAndroidImpl.java)
import android.graphics.Bitmap;
import com.github.anastaciocintra.escpos.image.CoffeeImage;
public class CoffeeImageAndroidImpl implements CoffeeImage {
private Bitmap bitmap;
public CoffeeImageAndroidImpl(Bitmap bitmap) {
this.bitmap = bitmap;
}
#Override
public int getWidth() {
return bitmap.getWidth();
}
#Override
public int getHeight() {
return bitmap.getHeight();
}
#Override
public CoffeeImage getSubimage(int x, int y, int w, int h) {
return new CoffeeImageAndroidImpl(bitmap.createBitmap(this.bitmap,x,y,w,h));
}
#Override
public int getRGB(int x, int y) {
return bitmap.getPixel(x, y);
}
}
and ... print with image like this:
...
BitmapFactory.Options options = new BitmapFactory.Options();
options.inScaled = false;
Bitmap bitmap = BitmapFactory.decodeResource(context.getResources(), R.drawable.dog, options);
RasterBitImageWrapper imageWrapper = new RasterBitImageWrapper();
escpos.writeLF("BitonalOrderedDither()");
// using ordered dither for dithering algorithm with default values
Bitonal algorithm = new BitonalOrderedDither();
EscPosImage escposImage = new EscPosImage(new CoffeeImageAndroidImpl(bitmap), algorithm);
escpos.write(imageWrapper, escposImage);
escpos.feed(5).cut(EscPos.CutMode.FULL);
...
read more and get github sample on: https://github.com/anastaciocintra/escpos-coffee/issues/9#issuecomment-541343942
I would like to try saving saving at a gifspeed, possibly bring up a box with speed selections, although i'm not quite sure how to change a gif speed using java.
I've looked this up but to no avail. I'm new so I'm sorry if this is a question and I just didn't find it
import base.AnimationExporter;
import java.awt.Dimension;
import java.awt.Graphics;
import settings.GuiDrawer;
public class SaveButton extends GuiElement
{
public SaveButton(GuiMenu parent)
{
super(parent);
}
public void releasedOn(int posX, int posY, int button)
{
if (heldDown) {
heldDown = false;
AnimationExporter.saveAnimation(true);
}
}
}
Edit: My bad heres AnimationExporter
try {
ImageWriter gifWriter = (ImageWriter)ImageIO.getImageWritersByFormatName("gif").next();
ImageOutputStream outputStream = ImageIO.createImageOutputStream(outputFile);
gifWriter.setOutput(outputStream);
ImageTypeSpecifier imageType = ImageTypeSpecifier.createFromBufferedImageType(2);
IIOMetadata metadata = gifWriter.getDefaultImageMetadata(imageType, null);
IIOMetadataNode nodeTree = (IIOMetadataNode)metadata.getAsTree(metadata.getNativeMetadataFormatName());
IIOMetadataNode appExtensionsNode = getNode("ApplicationExtensions", nodeTree);
IIOMetadataNode child = new IIOMetadataNode("ApplicationExtension");
child.setAttribute("applicationID", "NETSCAPE");
child.setAttribute("authenticationCode", "2.0");
child.setUserObject(new byte[] { 1, (byte)((Editing.animationLoop ? 0 : 1) & 0xFF), (byte)((Editing.animationLoop ? 0 : 1) >> 8 & 0xFF) });
appExtensionsNode.appendChild(child);
metadata.setFromTree(metadata.getNativeMetadataFormatName(), nodeTree);
gifWriter.prepareWriteSequence(null);
for (Frame frame : animation.Animation.frames) {
IIOMetadata imageMetadata = gifWriter.getDefaultImageMetadata(imageType, null);
IIOMetadataNode imageNodeTree = (IIOMetadataNode)imageMetadata.getAsTree(imageMetadata.getNativeMetadataFormatName());
IIOMetadataNode graphicNode = getNode("GraphicControlExtension", imageNodeTree);
graphicNode.setAttribute("disposalMethod", "none");
graphicNode.setAttribute("userInputFlag", "FALSE");
graphicNode.setAttribute("delayTime", Integer.toString(delay));
imageMetadata.setFromTree(imageMetadata.getNativeMetadataFormatName(), imageNodeTree);
IIOImage currentImage = new IIOImage(frame.getEntireFrame(), null, imageMetadata);
gifWriter.writeToSequence(currentImage, null);
}
gifWriter.endWriteSequence();
outputStream.close();
} catch (Exception e) {
e.printStackTrace();
}
}```
The framerate of the 'GIF' is embedded. However, you can speed it up or slow it down through external tools. Photoshop may work best. This tool may be able to help you. If you need dynamic framerate changes we need more information on the libraries you are using.
Ahh, so sorry I thought I had less copied down,l ooking at it now I feel dumb, delayTime here is,
public int delay = Editing.frameDelay;
I assume frameDelay is what I should change
public static int frameDelay = 100;
It goes like this: I'm developing an application that records chunks of video. When it detects that the free space has fallen under a certain treshold, it tries to delete old videos until the free amount of storage exceeds the threshold. If free storage falls under another threshold, lower than the first one, the app stops recording and displays a dialog informing about the lack of storage.
I have written a class that should help with these storage issues:
package net.ghetu.dasheye;
import java.io.File;
import java.util.Collections;
import java.util.Vector;
import android.content.Context;
import android.os.Environment;
import android.util.Log;
class StorageManager extends Thread {
private static final String TAG = "StorageManager";
private static File mediaStorageDir = new File(
Environment.getExternalStorageDirectory(), "DashEyeApp");
private static long totalSpace = mediaStorageDir.getTotalSpace();
private static long full99 = (long) (0.01 * totalSpace);
private static long full97 = (long) (0.03 * totalSpace);
private boolean isStopped = false;
private Vector<VideoItem> directoryEntries = null;
private GlobalState mAppState;
private PreviewService mPreviewService;
public void setStopped() {
isStopped = true;
}
public StorageManager(Context appState, PreviewService previewService) {
mAppState = (GlobalState) appState;
mPreviewService = previewService;
}
public static boolean hasRunOutOufSpace() {
long freeSpace = Environment.getExternalStorageDirectory()
.getFreeSpace();
if (freeSpace <= full99)
return true;
return false;
}
public static boolean hasLowSpace() {
long freeSpace = new File(Environment.getExternalStorageDirectory(),
"DashEyeApp").getFreeSpace();
Log.d(TAG,
"Free space: "
+ Long.toString((long) (freeSpace / (1024 * 1024)))
+ "MB");
if (freeSpace <= full97)
return true;
return false;
}
#Override
public void run() {
super.run();
while (!isStopped) {
if (hasLowSpace()) {
if (hasRunOutOufSpace()) {
if (mPreviewService != null) {
if (mAppState.isRecording()) {
mPreviewService.stopRecording();
mPreviewService.displayStorageDialog();
isStopped = true;
} else {
mPreviewService.displayStorageDialog();
isStopped = true;
}
}
} else {
if (mAppState.detectLoopModeActive()) {
Log.d(TAG, "Making space ...");
directoryEntries = getAllVideos();
Log.d(TAG, Integer.toString(directoryEntries.size()));
if (directoryEntries.size() > 1) {
directoryEntries.get(directoryEntries.size() - 1)
.getmFile().delete();
directoryEntries
.remove(directoryEntries.size() - 1);
}
directoryEntries.clear();
}
}
}
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private Vector<VideoItem> getAllVideos() {
Vector<VideoItem> directoryEntries = new Vector<VideoItem>();
File files[] = mediaStorageDir.listFiles();
if (files != null) {
if (files.length > 0) {
for (File file : files) {
if (VideoDetector.isVideo(file))
directoryEntries.add(new VideoItem(file));
}
Collections.sort(directoryEntries,
VideoItem.VideoDateComparatorDesc);
}
}
files = null;
Log.d(TAG,
"Fetching files: " + directoryEntries.size() + " files US: "
+ mediaStorageDir.getUsableSpace() + " FS: "
+ mediaStorageDir.getFreeSpace());
return directoryEntries;
}
}
My class, however, does not help me. What happens is: videos get deleted but hasLowSpace() still returns true. I. e.
long freeSpace = new File(Environment.getExternalStorageDirectory(),
"DashEyeApp").getFreeSpace();
Does not take into account the free space gained by deleting a video. Below, a sample of the log:
03-11 00:19:54.995: D/StorageManager(2863): Free space: 236MB
03-11 00:19:54.995: D/StorageManager(2863): Making space ...
03-11 00:19:55.015: D/StorageManager(2863): Fetching files: 3 files US: 248168448 FS: 248168448
03-11 00:19:55.015: D/StorageManager(2863): 3
03-11 00:20:00.015: D/StorageManager(2863): Free space: 230MB
03-11 00:20:00.015: D/StorageManager(2863): Making space ...
03-11 00:20:00.030: D/StorageManager(2863): Fetching files: 2 files US: 242081792 FS: 242081792
03-11 00:20:00.030: D/StorageManager(2863): 2
Notice that free space decreases while the number of videos in the folder also decreases.
Any ideas why this might be? At this point I'm desperate and willing to try everything. Experiencing this bug in Android 4.4.4 on a Samsung Galaxy i9305. Had the same problem on a Galaxy S1 GT-i9000 with a custom Android 4.4.4 ROM.
As android developer say "The getFreeSpace method returns the number of bytes potentially available to root". So you cannot use it without run as root. So i have a method to calculate the available block bytes.
public static float megabytesAvailable(File f) {
StatFs stat = new StatFs(f.getPath());
long bytesAvailable = (long)stat.getBlockSizeLong() * (long)stat.getAvailableBlocksLong();
return bytesAvailable / (1024.f * 1024.f);
}
Android Doc says that getFreeSpace() method returns the number of bytes potentially available to root, while getUsableSpace() returns the number of free bytes available to non-root users.
You can have a try to getUsableSpace().
Here are the two java classes:
package je3.io;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* Created by IDEA on 31/01/15.
*/
public class DirWalker {
private List<File> recursiveList = new ArrayList<File>();
public void walkDir(String pathname) {
File d = new File(pathname);
recursiveList.add(d);
if(d.isDirectory()) {
for(String f : d.list()) {
walkDir(f);
}
}
}
public void reset() {
recursiveList.clear();
}
public List<File> getRecursiveList() {
return recursiveList;
}
public static void main(String[] args) {
DirWalker dirWalker = new DirWalker();
dirWalker.walkDir("/tmp");
dirWalker.getRecursiveList().forEach(System.out::println);
}
}
package je3.io;
import java.io.File;
/**
* Created by IDEA on 31/01/15.
*/
public class DirSummariser {
private DirWalker dirWalker = new DirWalker();
private long dirSize = 0;
public DirSummariser(String pathname) {
dirWalker.reset();
dirWalker.walkDir(pathname);
}
public DirSummariser(File file) {
this(file.getAbsolutePath());
}
public long calculateDirSize() {
for(File f : dirWalker.getRecursiveList()) {
dirSize += f.length();
}
return dirSize;
}
public static void main(String[] args) {
DirSummariser dirSummariser = new DirSummariser("/Users/hualin/Downloads/pdf");
System.out.println(dirSummariser.calculateDirSize());
}
}
In the main method of the second class, I was trying to calculate the total size of the pdf folder, which should be around 30MB. The java program compiles without error, but says the size of the folder is only 1600 bytes.
The problem is in DirWalker:
public void walkDir(String pathname) {
File d = new File(pathname);
recursiveList.add(d);
if(d.isDirectory()) {
for(String f : d.list()) { // <-- here
walkDir(f); // <--
}
}
}
The strings returned by d.list() are just the file names, without a path attached to them. If you find, for example, a file some_directory/foo.txt, the string you'll pull out of the list is foo.txt, and since foo.txt is not in the current working directory, the File object you construct from it will be invalid (or describe a different file).
You'll have to make the path you're trying to inspect part of the recursion to make this work properly, for example like this:
walkDir(pathname + File.separator + f);
Or, as #Adam mentions in the comments, by passing the File object that describes the parent directory into the recursion and using the File(parent, child) constructor, as in
// new parameter here: parent directory
public void walkDir(String pathname, File parent) {
System.out.println(pathname);
File d = new File(parent, pathname); // <-- File constructor with parent
recursiveList.add(d);
if(d.isDirectory()) {
for(String f : d.list()) {
walkDir(f, d); // passing parent here
}
}
}
// entry point, to keep old interface.
public void walkDir(String pathname) {
walkDir(pathname, null);
}
Note: This answer, I think this should be mentioned, is rather tailored to OP's use case of an exercise, so I mainly tried to explain why his code didn't work and suggested ways to make it work. If you're a stray visitor in the future and looking for ways to walk through a directory with Java, look at #fge's answer for a better way.
Use the java.nio.file API, it's much better at doing things like this.
Here is an example, also using throwing-lambdas, calculating the total size of all files in a directory, recursively:
final Path theDirectory = Paths.get("path/to/your/directory");
final long totalSize = Files.walk(theDirectory)
.filter(Files::isRegularFile)
.mapToLong(Functions.rethrow(Files::size))
.sum();
If you don't have Java 8, use Files.walkFileTree().
I am developing a demo application with using GwtAI (Gwt Applet Integration). I have included all the GwtAI-client.jar,GwtAI-core.jar.I am referring to the http://code.google.com/p/gwtai/wiki/GettingStarted Following is the code.
FileUploadingApplet.class
#ImplementingClass(com.nextenders.appletImpl.FileUploadingAppletImpl.class)
#Height("60")
#Width("350")
#Archive("GwtAI-Client.jar,FileUploadingAppletImpl.jar")
#Codebase("applet")
public interface FileUploadingApplet extends Applet{
public void increment();
public void decrement();
public Object getCurrentValue();
}
FileUploadingAppletImpl.class
public class FileUploadingAppletImpl extends JApplet implements FileUploadingApplet {
JTextField m_fileNameTF = new JTextField(15);
String controlTransactionId = "";
JFileChooser m_fileChooser = new JFileChooser();
JPanel content = new JPanel();
FileWriter fstream = null;
long fileLength = 0l;
#Override
public void init() {
JPanel panelMain = new JPanel();
m_fileNameTF = new JTextField(20);
m_fileNameTF.setHorizontalAlignment(JTextField.CENTER);
m_fileNameTF.setText("0");
m_fileNameTF.setEditable(false);
panelMain.add(new JLabel("Current count : "));
panelMain.add(m_fileNameTF);
panelMain.setBorder(BorderFactory.createTitledBorder("CounterApplet"));
panelMain.setBackground(Color.WHITE);
getContentPane().add(panelMain);
}
public void increment() {
int currentCount = Integer.parseInt(m_fileNameTF.getText());
currentCount++;
m_fileNameTF.setText(currentCount + "");
}
public void decrement() {
int currentCount = Integer.parseInt(m_fileNameTF.getText());
currentCount--;
m_fileNameTF.setText(currentCount + "");
}
public Object getCurrentValue() {
return m_fileNameTF.getText();
}
}
NTFileUpload.java
private void createPanel(){
PopupPanel panel = new PopupPanel();
panel.setPopupPosition(500, 500);
panel.setHeight("600px");
panel.setHeight("900px");
final FileUploadingApplet fileUploadApplet = (FileUploadingApplet) GWT.create(FileUploadingApplet.class);
VerticalPanel panelMain = new VerticalPanel();
Button buttonInc = new Button("Increment");
buttonInc.addClickListener(new ClickListener() {
public void onClick(Widget sender) {
fileUploadApplet.increment();
}
});
Widget widgetApplet = AppletJSUtil.createAppletWidget(fileUploadApplet);
panelMain.add(widgetApplet);
panelMain.add(buttonInc);
panel.add(panelMain);
panel.show();
}
I have followed the package structure as per the link. But I am getting following Exception.
java.lang.IncompatibleClassChangeError: Found interface com.google.gwt.core.ext.typeinfo.JClassType, but class was expected
at com.google.gwt.gwtai.applet.generator.AppletProxyGenerator.generate(AppletProxyGenerator.java:71)
at com.google.gwt.core.ext.GeneratorExtWrapper.generate(GeneratorExtWrapper.java:48)
at com.google.gwt.core.ext.GeneratorExtWrapper.generateIncrementally(GeneratorExtWrapper.java:60)
at com.google.gwt.dev.javac.StandardGeneratorContext.runGeneratorIncrementally(StandardGeneratorContext.java:647)
at com.google.gwt.dev.cfg.RuleGenerateWith.realize(RuleGenerateWith.java:41)
at com.google.gwt.dev.shell.StandardRebindOracle$Rebinder.rebind(StandardRebindOracle.java:78)
at com.google.gwt.dev.shell.StandardRebindOracle.rebind(StandardRebindOracle.java:268)
at com.google.gwt.dev.shell.StandardRebindOracle.rebind(StandardRebindOracle.java:257)
at com.google.gwt.dev.DistillerRebindPermutationOracle.getAllPossibleRebindAnswers(DistillerRebindPermutationOracle.java:91)
at com.google.gwt.dev.jdt.WebModeCompilerFrontEnd.doFindAdditionalTypesUsingRebinds(WebModeCompilerFrontEnd.java:96)
at com.google.gwt.dev.jdt.AbstractCompiler$Sandbox$CompilerImpl.process(AbstractCompiler.java:254)
at org.eclipse.jdt.internal.compiler.Compiler.compile(Compiler.java:444)
at com.google.gwt.dev.jdt.AbstractCompiler$Sandbox$CompilerImpl.compile(AbstractCompiler.java:173)
at com.google.gwt.dev.jdt.AbstractCompiler$Sandbox$CompilerImpl.compile(AbstractCompiler.java:288)
at com.google.gwt.dev.jdt.AbstractCompiler$Sandbox$CompilerImpl.access$400(AbstractCompiler.java:139)
at com.google.gwt.dev.jdt.AbstractCompiler.compile(AbstractCompiler.java:588)
at com.google.gwt.dev.jdt.BasicWebModeCompiler.getCompilationUnitDeclarations(BasicWebModeCompiler.java:97)
at com.google.gwt.dev.jdt.WebModeCompilerFrontEnd.getCompilationUnitDeclarations(WebModeCompilerFrontEnd.java:52)
at com.google.gwt.dev.jjs.JavaToJavaScriptCompiler.precompile(JavaToJavaScriptCompiler.java:569)
at com.google.gwt.dev.jjs.JavaScriptCompiler.precompile(JavaScriptCompiler.java:33)
at com.google.gwt.dev.Precompile.precompile(Precompile.java:284)
at com.google.gwt.dev.Precompile.precompile(Precompile.java:233)
at com.google.gwt.dev.Precompile.precompile(Precompile.java:145)
at com.google.gwt.dev.Compiler.run(Compiler.java:232)
at com.google.gwt.dev.Compiler.run(Compiler.java:198)
at com.google.gwt.dev.Compiler$1.run(Compiler.java:170)
at com.google.gwt.dev.CompileTaskRunner.doRun(CompileTaskRunner.java:88)
at com.google.gwt.dev.CompileTaskRunner.runWithAppropriateLogger(CompileTaskRunner.java:82)
at com.google.gwt.dev.Compiler.main(Compiler.java:177)
Thanks in advance.
you need to build the dependencies that you're using (jar/war) with the same GWT SDK version that you are using for compilation of your project i.e. if 2.4 then use 2.4 to jar the dependencies and then compile your project. This error is due to the mismatch in the SDK versions being used.
There have been breaking changes in the GWT code generator feature, between version 1.7 and 2.0. So make sure you have the current version of GwtAI, if you work with a GWT version 2.0 or higher. If you work with a GWT version before 2.0 go to the GwtAI download page, select All downloads and click Search, you should see GwtAI 0.2 files. Those
should work with older GWT versions.