How to get all the media files on a computer - java

Is there a built in way to get all of the media files (movies , music) on a computer in java?

No, not build in. But, you could create a crawler that scans your entire hard drive for files with certain extensions ( or even better, MIME types ).
Check out this answer for an easy way to iterate through directories: https://stackoverflow.com/a/3154523/691606
See also Get the Mime Type from a File. Based on 1st 2 (of 3) techniques shown therein, is this:
import javax.activation.MimetypesFileTypeMap;
import java.io.File;
class MimeForMedia {
public static void main(String[] args) {
String[] types = {
"png", "jpg", "gif", "tif", "bmp", // image
"snd", "wav", "mp3", "ogg", "au", // sound
"mov", "avi", "mpg", "flv" // video
};
MimetypesFileTypeMap typeMap = new MimetypesFileTypeMap();
for (String type : types) {
String name = "a." + type;
String bestType = typeMap.getContentType(name);
if (bestType.equals("application/octet-stream")) {
System.out.print( "Using URLConnection: " );
try {
bestType = (new File(name)).toURI().toURL()
.openConnection().getContentType();
} catch(Exception e) {
System.out.println( e.getMessage() );
}
}
System.out.println (type + " " + bestType);
}
}
}
Here are the results on a Windows 7 PC.
Using URLConnection: png image/png
jpg image/jpeg
gif image/gif
tif image/tiff
Using URLConnection: bmp content/unknown
Using URLConnection: snd audio/basic
wav audio/x-wav
Using URLConnection: mp3 content/unknown
Using URLConnection: ogg content/unknown
au audio/basic
mov video/quicktime
avi video/x-msvideo
mpg video/mpeg
Using URLConnection: flv content/unknown
Press any key to continue . . .

Iterate on all the folders of your file system and look for files with the extensions you need (if you have time).

Related

File upload using zk 5.0.5

I am trying to upload jar file using zk(5.0.5). While uploading i have checked its format (extension) for that I have used getFormat() API of the Media (org.zkoss.util.media.Media).
code:
browsebtn.addEventListener("onUpload",new EventListener() {
public void onEvent(Event event) throws Exception {
private Media uploadedMedia;
uploadEvent=(UploadEvent) event;
uploadedMedia=uploadEvent.getMedia();
if(uploadedMedia!=null){
String fileName=uploadedMedia.getName();
fileFormat=uploadedMedia.getFormat();
System.out.println("File Format Name"+fileFormat);
}
}
});
Problem is that for internet explorer i get format as zip , for chrome and Firefox i get its format as octet-stream . Why there is such mismatching for different browsers . How to solve this problem ?(I dont want to any hard coding such as browser check)
You can try with;
LobData data = ZkUtils.media2LobData(uploadedMedia);
Then use that data:
data.getFormat();
I think the best way is to check the mime type to get the type, format, extension... of your file and to prevent some security attacks, for example you can use this :
File f = new File("test.pdf");
System.out.println("Mime Type of " + f.getName() + " is " +
new MimetypesFileTypeMap().getContentType(f));
// "Mime Type of test.pdf is application/pdf"
You can find here the list of the most popular mime types.
Hope this helps.

speech recognition with cmu sphinx - doesn't work properly

I'm trying to use CMU Sphinx for speech recognition in java but the result I'm getting is not correct and I don't know why.
I have a .wav file I recorded with my voice saying some sentence in English.
Here is my code in java:
Configuration configuration = new Configuration();
// Set path to acoustic model.
configuration.setAcousticModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us");
// Set path to dictionary.
configuration.setDictionaryPath("resource:/edu/cmu/sphinx/models/en-us/cmudict-en-us.dict");
// Set language model.
configuration.setLanguageModelPath("resource:/edu/cmu/sphinx/models/en-us/en-us.lm.dmp");
StreamSpeechRecognizer recognizer = new StreamSpeechRecognizer(configuration);
recognizer.startRecognition(new FileInputStream("assets/voice/some_wav_file.wav"));
SpeechResult result = null;
while ((result = recognizer.getResult()) != null) {
System.out.println("~~ RESULTS: " + result.getHypothesis());
}
recognizer.stopRecognition();
}
catch(Exception e){
System.out.println("ERROR: " + e.getMessage());
}
I also have another code in Android that doesn't work as well:
Assets assets = new Assets(context);
File assetDir = assets.syncAssets();
String prefix = assetDir.getPath();
Config c = Decoder.defaultConfig();
c.setString("-hmm", prefix + "/en-us-ptm");
c.setString("-lm", prefix + "/en-us.lm");
c.setString("-dict", prefix + "/cmudict-en-us.dict");
Decoder d = new Decoder(c);
InputStream stream = context.getResources().openRawResource(R.raw.some_wav_file);
d.startUtt();
byte[] b = new byte[4096];
try {
int nbytes;
while ((nbytes = stream.read(b)) >= 0) {
ByteBuffer bb = ByteBuffer.wrap(b, 0, nbytes);
short[] s = new short[nbytes/2];
bb.asShortBuffer().get(s);
d.processRaw(s, nbytes/2, false, false);
}
} catch (IOException e) {
Log.d("ERROR: ", "Error when reading file" + e.getMessage());
}
d.endUtt();
Log.d("TOTAL RESULT: ", d.hyp().getHypstr());
for (Segment seg : d.seg()) {
Log.d("RESULT: ", seg.getWord());
}
I used this website to convert the wav file to 16bit, 16khz, mono and little-endian (tried all the options of it).
Any ideas why is doesn't work. I use the built in dictionaries and accustic models and my accent in English is not perfect (don't know if it matters).
EDIT:
This is my file. I recorded myself saying: "My baby is cute" and that's what I expect to be the output.
In the pure java code I get: "i've amy's youth" and in the android code I getl: " it"
Here is file containing the logs.
Your audio is somewhat corrupted by conversion. You should record into wav originally or into some other lossless format. Your pronunciation is also far from US English. For conversion between formats you can use sox instead of external website. Your android sample seems correct but it feels like you decode different file with android. You might check that you have actual proper file in resources.

How to converting TIFF image file to Bitmap Android

I would like to convert images on SDcard to bitmap. I am using below code
String filepath = "/storage/emulated/0/Download/sample2.tif";
Bitmap bm = BitmapFactory.decodeFile(filepath);
This code is working fine for file with extension .jpg or .png but not for .tif or .tiff. For TIFF files bmbecomes null no exceptions nothing all file paths are valid.
Is there any limitation in Android BitmapFactory with respect to decoding TIFF images?
Also tried decodeByteArray and decodeStream, looks like limitation for me.
I am able to read TIFF image file as byte [] but conversion of byte[] or file input stream as bitmap is returning null
Please let me know any other way to convert TIFF Image file to Bitmap.
As VERT9x said TIFF files are not supported on android. But you can convert them back or forth using native android library like https://github.com/puelocesar/android-lib-magick . This is sample code to convert jpg to tif. Hope this helps.
MagickImage Image = new MagickImage(new ImageInfo(IMAGE_PATH));
// Image = Image.scaleImage(800, 800);
Image.setImageFormat("tif");
Image.setFileName(str);
ImageInfo localImageInfo = new ImageInfo(str);
localImageInfo.setMagick("tif");
Image.writeImage(localImageInfo);
// store as tif
byte[] blob = Image.imageToBlob(localImageInfo);
FileOutputStream localFileOutputStream = new FileOutputStream(str);
localFileOutputStream.write(blob);
localFileOutputStream.close();
To decode a simple color tif file go as below:
String taginfo="";String strVal=""; //These are Tiff Tags
FileInputStream fis;BufferedInputStream bis;DataInputStream dis;
path=Environment.getExternalStorageDirectory().getPath();
path=path+"/DCIM"+"/fileName.tif"; //whatever is your file-name.tif
try{
fis=new FileInputStream(path);
bis=new bufferedInputStream(fis);
dis=new DataInputStream(bis);
dis.skip(4); //skip 4 byte marker of TIFF+endian
ifd=myInt(dis.readInt()); //read the 4 byte IFD-location
txt="TIFF-IFD: "; //txt is the final text displayed in textView
txt=txt+ifd;
dis.skip(ifd-8);
entries=myShort(dis.readShort()); //read in your endian-style
txt=txt+"\nNo.OfEntries="+entries;
for(int i=0;i<=entries;i++)
{
tag=myShort( dis.readShort() );
taginfo=tagInfo(tag); //tagInfo function returns info associated
//with tag
type=myShort( dis.readShort() );
count=myInt( dis.readInt() );
value=myInt( dis.readInt() );
if(type==3)strVal="Value="; else strVal="Offset=";
if( strVal.equals("Offset=") )
{
if( taginfo.equals("StripOffsets") ) //image is stored as
{stripAt=value;stripCount=count;} // strips of rows
if( taginfo.equals("StripBytes") )
{stripBytesAt=value;}
}
if( taginfo.equals("width") ){cols=value;}
if( taginfo.equals("length") ){rows=value;}
txt=txt+"\ntag="+tag+"" + tagInfo(tag) + ",type=" + type +
",count=" + count + strVal + value;
}
dis.close();bis.close();fis.close();
}catch(Exception e) { txt = txt + "\nerror=" + e.toString(); }
txt=txt+"\nNo.OfStrips="+stripCount+",array of strip locations at:
"+stripAt+" and array of bytesPerStrip at "+stripBytesAt ;
extractBMP(); // a function you will define to combine all strips to
//bitmap image
}
public int myShort(short sh)
{ int i;
ByteBuffer shortBuff=ByteBuffer.allocate(4);
shortBuff.order(ByteOrder.BIG_ENDIAN);shortBuff.putShort(sh);shortBuff.rewind();
shortBuff.order(ByteOrder.LITTLE_ENDIAN);sh=shortBuff.getShort();
if(sh<0)i=(int)(sh+32768); else i=(int)sh;
return i;
}
public long myInt(int i)
{ long l=0L;
ByteBuffer intBuff=ByteBuffer.allocate(4);
intBuff.order(ByteOrder.BIG_ENDIAN);intBuff.putInt(i);intBuff.rewind();
intBuff.order(ByteOrder.LITTLE_ENDIAN); i=intBuff.getInt();
if(i<0)l=(long)(i+2147483648L); else l=(long)i;
return l;
}
public String tagInfo(int tag)
{ int i=0;
switch(tag)
{case 256: i=0;break;case 257: i=1;break;case 258: i=2;break;case 259: i=3;break;case 262: i=4;break;case 266: i=5;break;
case 273: i=6;break;case 277: i=7;break;case 278: i=8;break;case 279: i=9;break;case 282: i=10;break;case 283: i=11;break;
case 284: i=12;break;case 296: i=13;break;case 1496: i=14;break;case 0: i=15;break;
}
return info[i];
}
If you wish to see the full code then see here:
Decode Tiff Image in Android Java Code
TIFF files are not supported natively on Android. Check the list of supported media formats.
If you want to support TIFF files you'll have to decode them manually yourself or find a library that does it for you.
Try to use my lib. It support dirrect convert from tiff to jpg/png/bmp
https://github.com/Beyka/Android-TiffBitmapFactory

Print PDF that contains JBIG2 images

Please, suggest me some libraries that will help me print PDF files that contain JBIG2 encoded images. PDFRenderer, PDFBox don't help me. These libs can print simple PDF, but not PDF containing JBIG2 images. PDFRenderer tries to fix it (according to bug issue on PDFRedndrer's bug tracker), but some pages still (especially where barcodes exist) don't want to print.
P.S. I use javax.print API within applet
Thanks!
UPDATE: also tried ICEPdf, is too don't want to work.
I came to the conclusion that all these libraries(PDFRenderer, ICEPdf, PDFBox) use JPedals jbig2 decoder. Bug (some pages didn't print) come from this decoder library. The open source version of this decoder (which is used in PDFRenderer, ICEPdf, PDFBox) is no longer supported, but JPedal has a new commercial branch of the project, and they wrote that the bug has been fixed in new commercial release, which costs $9k.
Any ideas?
UPDATE 2: yesterday I tried to replace JPedal's free library with other open-source jbig2-imageio libraries. But yet I don't get any successful results, so I created a new topic on their project's page (google-code's forum - here ). Would be grateful for any help.
I also found some helpfull discussions on Apache PDFBox bug-tracker: here and here.
As going through your comment in yms answer ie. " but what library I can use to extract images and (more importantly) put them back in PDF?"
Here is a simple demonstration of
1 ) Extracting jbig2 or you can say all images from pdf.
2 ) Converting jbig2 image to any other format, in my case its jpeg.
3 ) Creating new pdf containing the jpeg.
Using libraries jbig2-imageio and itext.
In the below example please change the resources and the directories path as per your need.
For this I had to go through several resources that I will attach in the end. Hope this helps.
import com.itextpdf.text.Document;
import com.itextpdf.text.Image;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.text.pdf.parser.*;
import com.levigo.jbig2.JBIG2ImageReader;
import com.levigo.jbig2.JBIG2ImageReaderSpi;
import com.levigo.jbig2.JBIG2ReadParam;
import com.levigo.jbig2.io.DefaultInputStreamFactory;
import java.awt.image.BufferedImage;
import java.io.*;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageInputStream;
public class JBig2Image {
private String filepath;
private int imageIndex;
public JBig2Image() {
this.filepath = "/home/blackadmin/Desktop/pdf/demo18.jbig2";
this.imageIndex = 0;
extractImgFromPdf();
convertJBig2ToJpeg();
createPDF();
}
private void extractImgFromPdf() {
try {
/////////// Extract all Images from pdf /////////////////////////
PdfReader reader = new PdfReader("/home/blackadmin/Desktop/pdf/orig.pdf");
PdfReaderContentParser parser = new PdfReaderContentParser(reader);
MyImageRenderListener listener = new MyImageRenderListener("/home/blackadmin/Desktop/pdf/demo%s.%s");
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
parser.processContent(i, listener);
}
} catch (IOException ex) {
System.out.println(ex);
}
}
private void convertJBig2ToJpeg() {
InputStream inputStream = null;
try {
///////// Read jbig2 image ////////////////////////////////////////
inputStream = new FileInputStream(new File(filepath));
DefaultInputStreamFactory disf = new DefaultInputStreamFactory();
ImageInputStream imageInputStream = disf.getInputStream(inputStream);
JBIG2ImageReader imageReader = new JBIG2ImageReader(new JBIG2ImageReaderSpi());
imageReader.setInput(imageInputStream);
JBIG2ReadParam param = imageReader.getDefaultReadParam();
BufferedImage bufferedImage = imageReader.read(imageIndex, param);
////////// jbig2 to jpeg ///////////////////////////////////////////
ImageIO.write(bufferedImage, "jpeg", new File("/home/blackadmin/Desktop/pdf/demo18.jpeg"));
} catch (IOException ex) {
System.out.println(ex);
} finally {
try {
inputStream.close();
} catch (IOException ex) {
System.out.println(ex);
}
}
}
public void createPDF() {
Document document = new Document();
try {
PdfWriter.getInstance(document,
new FileOutputStream("/home/blackadmin/Desktop/pdf/output.pdf"));
document.open();
PdfPTable table = new PdfPTable(1); //1 column.
Image image = Image.getInstance("/home/blackadmin/Desktop/pdf/demo18.jpeg");
image.scaleToFit(800f, 600f);
image.scaleAbsolute(800f, 600f); // Give the size of image you want to print on pdf
PdfPCell nestedImgCell = new PdfPCell(image);
table.addCell(nestedImgCell);
document.add(table);
document.close();
System.out.println(
"======== PDF Created Successfully =========");
} catch (Exception e) {
System.out.println(e);
}
}
public static void main(String[] args) throws IOException {
new JBig2Image();
}
}
class MyImageRenderListener implements RenderListener {
/**
* The new document to which we've added a border rectangle.
*/
protected String path = "";
/**
* Creates a RenderListener that will look for images.
*/
public MyImageRenderListener(String path) {
this.path = path;
}
/**
* #see com.itextpdf.text.pdf.parser.RenderListener#beginTextBlock()
*/
public void beginTextBlock() {
}
/**
* #see com.itextpdf.text.pdf.parser.RenderListener#endTextBlock()
*/
public void endTextBlock() {
}
/**
* #see com.itextpdf.text.pdf.parser.RenderListener#renderImage(
* com.itextpdf.text.pdf.parser.ImageRenderInfo)
*/
public void renderImage(ImageRenderInfo renderInfo) {
try {
String filename;
FileOutputStream os;
PdfImageObject image = renderInfo.getImage();
if (image == null) {
return;
}
filename = String.format(path, renderInfo.getRef().getNumber(), image.getFileType());
os = new FileOutputStream(filename);
os.write(image.getImageAsBytes());
os.flush();
os.close();
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
/**
* #see com.itextpdf.text.pdf.parser.RenderListener#renderText(
* com.itextpdf.text.pdf.parser.TextRenderInfo)
*/
public void renderText(TextRenderInfo renderInfo) {
}
}
References :
1 ) Extracting jbig2 from pdf (extract images) (MyImageRenderListener).
2 ) Converting jbig2 (JBIG2ImageReaderDemo)
There is a fork of the JPedal library by Borisvl located at
https://github.com/Borisvl/JBIG2-Image-Decoder#readme
which contains speed improvements and I believe it should also fix your bug.
EDIT : The bug is related to simple range checking. Basically you need to prevent GetPixel from accessing x,y values outside of the bitmap extents.
You need to make sure the following conditions are met before calling getPixel
col >= 0 and col < bitmap.width
row >= 0 and row < bitmap.height
Here is some Delphi code with a couple of small range checks. I cannot test the Java code myself but you need to make changes to src/org/jpedal/jbig2/image/JBIG2Bitmap.java
procedure TJBIG2Bitmap.combine(bitmap: TJBIG2Bitmap; x, y: Integer; combOp: Int64);
...
...
var
begin
srcWidth := bitmap.width;
srcHeight := bitmap.height;
srcRow := 0;
srcCol := 0;
if (x < 0) then x := 0;
if (y < 0) then y := 0;
for row := y to Min(y + srcHeight - 1, Self.height - 1) do // <<<<<<<< HERE
begin
for col := x to x + srcWidth - 1 do
begin
srcPixel := bitmap.getPixel(srcCol, srcRow);
Andrew.
How about using AcrobatReader itself? It's a bit muddy getting it to work, and not a robust solution I guess. But will probably print all of it perfectly. And be free
Some info about this route;
http://vineetreynolds.blogspot.nl/2005/12/silent-print-pdf-print-pdf.html
http://www.codeproject.com/Questions/98586/Programmatically-print-PDF-documents
http://forums.adobe.com/message/2336723
You have tools as ImageMagick which handle images and convert them to a lot of formats. I used it some years ago so I can't tell you if the jbig2 format is properly handled by default or if you have to install some plugin.
You can try the following to have a list of supported formats beginning with J like the JBIG2 you are searching for:
$ convert -list format | grep -i J
It is really obvious to convert to pdf with with tool too, coupled with gs tool aka GhostScript.
If fact nothing prevent you to display a PNG/JPEG version of the image and provide a download link to the original JBIG2 file with its own metadatas.
As an alternative, you could try doing this server-side:
Approach 1:
Convert the PDF files to raster images using an external application and print that instead.
Approach 2:
Adjust your PDF files by recompressing JBIG2 images:
1- Extracting the images compressed as JBIG2 from your files.
2- Re-compress them with some other algorithm (jpeg, png, etc). In order to do this you might need to go outside of Java using either JNI or calling an external application. You can try with jbig2dec or ImageMagic for example if the GPL lincense suits your needs.
3- Put the recompressed images back in your PDF.
This approach will imply some quality loss on those images, but at least you will be able to print the files.
You can do this in Java with iText, there is a chapter about resizing images in the book iText in Action (with sample code). The idea there is to extract the image, resize it (including recompression) and put it back. You can use this as starting point. Be aware that iText is an AGPL project, hence you cannot use it for free in commercial closed-source applications.
If you are using a Windows-based server and you can afford a commercial tool, you can also achieve this with Amyuni PDF Creator either with C#/VB.Net or C++ (Usual disclaimer applies for this suggestion). You just need to go though all objects of type acObjectTypePicture and set the attribute Compression to acJPegHigh, this approach does not require any external JBIG2 decoder, (I can include some sample code here if you are interested).
If you are using an applet just to print your PDF files, you could also try generating a PDF file that shows the print dialog when opened

How do you Edit Video ID3v2 Tags in Java

I have been doing some research on ID3V2 tags and Video Formats such as MP4 and WMV. The two top libraries for editing ID3V2 tags seem to be:
Entagged and Jaudiotagger
Both of these support only audio formats. ( They support M4A and WMA but not MP4 and WMV ) I guess first off why is this? Then are they any alternatives.
It appears JID3 will do the trick. It doesn't have any restrictions on extension.
http://jid3.blinkenlights.org/
Now hopefully someone finds this open-source project a designer!
Here is an example of using it with several different file formats:
public class JITExample {
private static MediaFile audioFile;
public static void main(String... megaThrustersAreGo) {
//File file = new File("/home/rhigdon/Desktop/project-voltron/test-files/video.mp4");
//File file = new File("/home/rhigdon/Desktop/project-voltron/test-files/movGetOutTheWay_iPhone_Cellular_1.3gp");
File file = new File("/home/rhigdon/Desktop/project-voltron/test-files/movGetOutTheWay_HD_WMV_720p_1.wmv");
//Entagged Soltuion
audioFile = new MP3File(file);
try {
ID3V2_3_0Tag tag = new ID3V2_3_0Tag();
tag.setArtist("Ryan Higdon");
tag.setAlbum("Ryan's Funky Beats");
audioFile.setID3Tag(tag);
audioFile.sync();
for (ID3Tag eachTag : audioFile.getTags()) {
System.out.println(eachTag.toString());
}
} catch (ID3Exception e) {
e.printStackTrace();
System.out.println("something bad happened");
}
}
}
According to the introduction page here http://www.id3.org/Introduction, ogg, wma and aac uses their own formats separated from ID3v2.
Another library for editing ID3v2 and playing mp3:s is JLayer. It doesn't need JMF and it is available for both J2SE and J2ME.

Categories