Is there a way to change Gif speed - java

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;

Related

Change font in pptx slide master in Apache POI

I am using Apache POI to modify a pptx. I would like to change the font of the whole pptx at once.
I know in Powerpoint this is possible by changing the fonts of the theme (if the slides all use these fonts), but I cannot make it work through Apache POI.
What I found so far is that I can set the font family of a single XSLFTextRun by using e.g. run.setFontFamily(HSSFFont.FONT_ARIAL).
Edit: I found that the XSLFTheme Class of the XSLFSlideMaster does have a getMajorFont() and a getMinorFont() method. I think these might be the fonts I need to change, but there are no setters for these fields.
Thanks for your help!
If your attempt is to do the same as Change the default font in PowerPoint, then this changes the major font and the minor font of the font scheme in used theme.
You can get XSLFTheme from each slide of the slide show, so also from the master. But as you found already there are getters but no setters for major font and minor font. So we need using low level ooxml-schemas classes.
Following code example provides setMajorFont and setMinorFont method which sets type face of major font and minor font in the theme for either Latin script, east Asia script or complex script.
import java.io.FileInputStream;
import java.io.FileOutputStream;
import org.apache.poi.xslf.usermodel.*;
import org.openxmlformats.schemas.drawingml.x2006.main.*;
public class PowerPointChangeThemeFonts {
enum Script {
LATIN, //Latin script
EA, //east Asia script
CS //complex script
}
static void setMajorFont(XSLFTheme theme, Script script, String typeFace) {
CTOfficeStyleSheet styleSheet = theme.getXmlObject();
CTBaseStyles themeElements = styleSheet.getThemeElements();
CTFontScheme fontScheme = themeElements.getFontScheme();
CTFontCollection fontCollection = fontScheme.getMajorFont();
CTTextFont textFont = null;
if (script == Script.LATIN) {
textFont = fontCollection.getLatin();
textFont.setTypeface(typeFace);
} else if (script == Script.EA) {
textFont = fontCollection.getEa();
textFont.setTypeface(typeFace);
} else if (script == Script.CS) {
textFont = fontCollection.getCs();
textFont.setTypeface(typeFace);
}
}
static void setMinorFont(XSLFTheme theme, Script script, String typeFace) {
CTOfficeStyleSheet styleSheet = theme.getXmlObject();
CTBaseStyles themeElements = styleSheet.getThemeElements();
CTFontScheme fontScheme = themeElements.getFontScheme();
CTFontCollection fontCollection = fontScheme.getMinorFont();
CTTextFont textFont = null;
if (script == Script.LATIN) {
textFont = fontCollection.getLatin();
textFont.setTypeface(typeFace);
} else if (script == Script.EA) {
textFont = fontCollection.getEa();
textFont.setTypeface(typeFace);
} else if (script == Script.CS) {
textFont = fontCollection.getCs();
textFont.setTypeface(typeFace);
}
}
public static void main(String args[]) throws Exception {
XMLSlideShow slideShow = new XMLSlideShow(new FileInputStream("./PPTX.pptx"));
if (slideShow.getSlideMasters().size() > 0) {
XSLFSlideMaster master = slideShow.getSlideMasters().get(0);
XSLFTheme theme = master.getTheme();
setMajorFont(theme, Script.LATIN, "Courier New");
setMinorFont(theme, Script.LATIN, "Courier New");
}
FileOutputStream out = new FileOutputStream("./PPTXNew.pptx");
slideShow.write(out);
out.close();
slideShow.close();
}
}

MethodHandle.invoke and MethodHandle.invokeExact are only supported starting with Android O (--min-api 26)

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

Android - Free space for external storage not displaying correctly

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().

Why is this not calculating total size of the folder correctly?

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().

Why is my Xuggle video converter not working

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)

Categories

Resources