Example usage for android.webkit MimeTypeMap getExtensionFromMimeType

List of usage examples for android.webkit MimeTypeMap getExtensionFromMimeType

Introduction

In this page you can find the example usage for android.webkit MimeTypeMap getExtensionFromMimeType.

Prototype

@Nullable
public String getExtensionFromMimeType(String mimeType) 

Source Link

Document

Return the registered extension for the given MIME type.

Usage

From source file:Main.java

public static String assetMimeTypeToExtension(String mimeType) {
    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    String extension = mimeTypeMap.getExtensionFromMimeType(mimeType);
    if (extension == null) {
        return mimeType;
    }//  www  . j a  va2 s  . c  om
    return extension;
}

From source file:org.mariotaku.twidere.util.SaveImageTask.java

public static File saveImage(final Context context, final File image_file) {
    if (context == null && image_file == null)
        return null;
    try {/*from w ww  . j a  v a2 s .  co  m*/
        final String name = image_file.getName();
        if (isEmpty(name))
            return null;
        final String mime_type = getImageMimeType(image_file);
        final MimeTypeMap map = MimeTypeMap.getSingleton();
        final String extension = map.getExtensionFromMimeType(mime_type);
        if (extension == null)
            return null;
        final String name_to_save = name.indexOf(".") != -1 ? name : name + "." + extension;
        final File pub_dir = EnvironmentAccessor
                .getExternalStoragePublicDirectory(EnvironmentAccessor.DIRECTORY_PICTURES);
        if (pub_dir == null)
            return null;
        final File save_dir = new File(pub_dir, "Twidere");
        if (!save_dir.isDirectory() && !save_dir.mkdirs())
            return null;
        final File save_file = new File(save_dir, name_to_save);
        FileUtils.copyFile(image_file, save_file);
        if (save_file != null && mime_type != null) {
            MediaScannerConnectionAccessor.scanFile(context, new String[] { save_file.getPath() },
                    new String[] { mime_type }, null);
        }
        return save_file;
    } catch (final IOException e) {
        Log.w(LOGTAG, "Failed to save file", e);
        return null;
    }
}

From source file:org.mariotaku.twidere.util.SaveFileTask.java

public static SaveFileTask saveImage(final Activity activity, final File source) {
    final String mimeType = Utils.getImageMimeType(source);
    final MimeTypeMap map = MimeTypeMap.getSingleton();
    final String extension = map.getExtensionFromMimeType(mimeType);
    if (extension == null)
        return null;
    final File pubDir = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES);
    final File saveDir = new File(pubDir, "Twidere");
    return new SaveFileTask(activity, source, mimeType, saveDir);
}

From source file:org.mariotaku.twidere.util.SaveFileTask.java

public static File saveFile(final Context context, final File source, final String mimeType,
        final File destination) {
    if (context == null && source == null)
        return null;
    Source ioSrc = null;//w w  w . j  a va  2s .  c o  m
    BufferedSink sink = null;
    try {
        final String name = source.getName();
        if (isEmpty(name))
            return null;
        final MimeTypeMap map = MimeTypeMap.getSingleton();
        final String extension = map.getExtensionFromMimeType(mimeType);
        if (extension == null)
            return null;
        final String nameToSave = getFileNameWithExtension(name, extension);
        if (!destination.isDirectory() && !destination.mkdirs())
            return null;
        final File saveFile = new File(destination, nameToSave);
        ioSrc = Okio.source(source);
        sink = Okio.buffer(Okio.sink(saveFile));
        sink.writeAll(ioSrc);
        sink.flush();
        if (mimeType != null) {
            MediaScannerConnection.scanFile(context, new String[] { saveFile.getPath() },
                    new String[] { mimeType }, null);
        }
        return saveFile;
    } catch (final IOException e) {
        final int errno = Utils.getErrorNo(e.getCause());
        Log.w(LOGTAG, "Failed to save file", e);
        return null;
    } finally {
        Utils.closeSilently(sink);
        Utils.closeSilently(ioSrc);
    }
}

From source file:mobisocial.musubi.objects.FileObj.java

public static Obj from(Context context, Uri dataUri) throws IOException {
    //TODO: is this the proper way to do it?
    if (dataUri == null) {
        throw new NullPointerException();
    }/*  w ww .  j  a  v a  2  s. c o m*/
    ContentResolver cr = context.getContentResolver();
    InputStream in = cr.openInputStream(dataUri);
    long length = in.available();

    String ext;
    String mimeType;
    String filename;

    MimeTypeMap mimeTypeMap = MimeTypeMap.getSingleton();
    if ("content".equals(dataUri.getScheme())) {
        ContentResolver resolver = context.getContentResolver();
        mimeType = resolver.getType(dataUri);
        ext = mimeTypeMap.getExtensionFromMimeType(mimeType);
        filename = "Musubi-" + sDateFormat.format(new Date());
    } else {
        ext = MimeTypeMap.getFileExtensionFromUrl(dataUri.toString());
        mimeType = mimeTypeMap.getMimeTypeFromExtension(ext);
        filename = Uri.parse(dataUri.toString()).getLastPathSegment();
        if (filename == null) {
            filename = "Musubi-" + sDateFormat.format(new Date());
        }
    }

    if (mimeType == null || mimeType.isEmpty()) {
        throw new IOException("Unidentified mime type");
    }

    if (ext == null || ext.isEmpty()) {
        ext = mimeTypeMap.getExtensionFromMimeType(mimeType);
    }

    if (!ext.isEmpty() && !filename.endsWith(ext)) {
        filename = filename + "." + ext;
    }

    if (mimeType.startsWith("video/")) {
        return VideoObj.from(context, dataUri, mimeType);
    } else if (mimeType.startsWith("image/")) {
        return PictureObj.from(context, dataUri, true);
    }

    if (length > EMBED_SIZE_LIMIT) {
        if (length > CORRAL_SIZE_LIMIT) {
            throw new IOException("file too large for push");
        } else {
            return fromCorral(context, mimeType, filename, length, dataUri);
        }
    } else {
        in = cr.openInputStream(dataUri);
        return from(mimeType, filename, length, IOUtils.toByteArray(in));
    }
}

From source file:mil.nga.giat.mage.sdk.utils.MediaUtility.java

public static File copyMediaFromUri(Context context, Uri uri) throws IOException {
    InputStream is = null;//from ww w . j av a  2  s  .  co  m
    OutputStream os = null;
    try {
        ContentResolver contentResolver = context.getContentResolver();

        String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss").format(new Date());
        String imageFileName = "MAGE_" + timeStamp;

        MimeTypeMap mime = MimeTypeMap.getSingleton();
        String extension = "." + mime.getExtensionFromMimeType(contentResolver.getType(uri));

        File directory = context.getExternalFilesDir("media");
        File file = File.createTempFile(imageFileName, /* prefix */
                extension, /* suffix */
                directory /* directory */
        );

        is = contentResolver.openInputStream(uri);
        os = new FileOutputStream(file);
        ByteStreams.copy(is, os);

        return file;
    } finally {
        if (is != null) {
            try {
                is.close();
            } catch (IOException e) {
            }
        }

        if (os != null) {
            try {
                os.close();
            } catch (IOException e) {
            }
        }
    }
}

From source file:com.zhihu.matisse.MimeType.java

public boolean checkType(ContentResolver resolver, Uri uri) {
    MimeTypeMap map = MimeTypeMap.getSingleton();
    if (uri == null) {
        return false;
    }/*w  w  w .j  av  a 2s . c  o m*/
    String type = map.getExtensionFromMimeType(resolver.getType(uri));
    String path = null;
    // lazy load the path and prevent resolve for multiple times
    boolean pathParsed = false;
    for (String extension : mExtensions) {
        if (extension.equals(type)) {
            return true;
        }
        if (!pathParsed) {
            // we only resolve the path for one time
            path = PhotoMetadataUtils.getPath(resolver, uri);
            if (!TextUtils.isEmpty(path)) {
                path = path.toLowerCase(Locale.US);
            }
            pathParsed = true;
        }
        if (path != null && path.endsWith(extension)) {
            return true;
        }
    }
    return false;
}

From source file:com.apptentive.android.sdk.model.FileMessage.java

public boolean createStoredFile(Context context, String uriString) {
    Uri uri = Uri.parse(uriString);/* w w  w  . j a v  a 2 s . co  m*/

    ContentResolver resolver = context.getContentResolver();
    String mimeType = resolver.getType(uri);
    MimeTypeMap mime = MimeTypeMap.getSingleton();
    String extension = mime.getExtensionFromMimeType(mimeType);

    // If we can't get the mime type from the uri, try getting it from the extension.
    if (extension == null) {
        extension = MimeTypeMap.getFileExtensionFromUrl(uriString);
    }
    if (mimeType == null && extension != null) {
        mimeType = mime.getMimeTypeFromExtension(extension);
    }

    setFileName(uri.getLastPathSegment() + "." + extension);
    setMimeType(mimeType);

    InputStream is = null;
    try {
        is = new BufferedInputStream(context.getContentResolver().openInputStream(uri));
        return createStoredFile(context, is, mimeType);
    } catch (FileNotFoundException e) {
        Log.e("File not found while storing file.", e);
    } catch (IOException e) {
        Log.a("Error storing image.", e);
    } finally {
        Util.ensureClosed(is);
    }
    return false;
}

From source file:org.zywx.wbpalmstar.engine.EDownloadDialog.java

private void saveToFile() throws Exception {
    mInStream = mConnection.getInputStream();
    if (mInStream == null) {
        return;//from ww w  .ja v  a 2 s . c o  m
    }
    if (contentLength <= 0) {
        String cLength = mConnection.getHeaderField("Content-Length");
        if (cLength != null) {
            contentLength = Long.parseLong(cLength);
        }
    }
    MimeTypeMap mtm = MimeTypeMap.getSingleton();
    String extension = mtm.getExtensionFromMimeType(mimetype);
    File tm = Environment.getExternalStorageDirectory();
    File target = new File(tm.getAbsoluteFile() + "/Download/");
    if (!target.exists()) {
        target.mkdirs();
    }
    mTmpFile = File.createTempFile("/Download/", "." + extension, tm);
    OutputStream outStream = new FileOutputStream(mTmpFile);
    byte buffer[] = new byte[1024 * 3];
    while (true) {
        int numread = mInStream.read(buffer);
        if (numread == -1) {
            mProgressHandler.sendEmptyMessage(100);
            break;
        }
        outStream.write(buffer, 0, numread);
        downLoaderSise += numread;
        int p = (int) (((float) downLoaderSise / contentLength) * 100);
        mProgressHandler.sendEmptyMessage(p);
    }
    if (contentLength <= 0) {
        mProgressHandler.sendEmptyMessage(100);
    }
}

From source file:com.apptentive.android.sdk.model.FileMessage.java

/**
 * This method stores an image, and compresses it in the process so it doesn't fill up the disk. Therefore, do not use
 * it to store an exact copy of the file in question.
 *///ww  w . j a  v a  2s  .c  o m
public boolean internalCreateStoredImage(Context context, String uriString) {
    Uri uri = Uri.parse(uriString);

    ContentResolver resolver = context.getContentResolver();
    String mimeType = resolver.getType(uri);
    MimeTypeMap mime = MimeTypeMap.getSingleton();
    String extension = mime.getExtensionFromMimeType(mimeType);
    setFileName(uri.getLastPathSegment() + "." + extension);
    setMimeType(mimeType);

    // Create a file to save locally.
    String localFileName = getStoredFileId();
    File localFile = new File(localFileName);

    // Copy the file contents over.
    InputStream is = null;
    CountingOutputStream cos = null;
    try {
        is = new BufferedInputStream(context.getContentResolver().openInputStream(uri));
        cos = new CountingOutputStream(
                new BufferedOutputStream(context.openFileOutput(localFile.getPath(), Context.MODE_PRIVATE)));
        System.gc();
        Bitmap smaller = ImageUtil.createScaledBitmapFromStream(is, MAX_STORED_IMAGE_EDGE,
                MAX_STORED_IMAGE_EDGE, null);
        // TODO: Is JPEG what we want here?
        smaller.compress(Bitmap.CompressFormat.JPEG, 95, cos);
        cos.flush();
        Log.d("Bitmap saved, size = " + (cos.getBytesWritten() / 1024) + "k");
        smaller.recycle();
        System.gc();
    } catch (FileNotFoundException e) {
        Log.e("File not found while storing image.", e);
        return false;
    } catch (Exception e) {
        Log.a("Error storing image.", e);
        return false;
    } finally {
        Util.ensureClosed(is);
        Util.ensureClosed(cos);
    }

    // Create a StoredFile database entry for this locally saved file.
    StoredFile storedFile = new StoredFile();
    storedFile.setId(getStoredFileId());
    storedFile.setOriginalUri(uri.toString());
    storedFile.setLocalFilePath(localFile.getPath());
    storedFile.setMimeType("image/jpeg");
    FileStore db = ApptentiveDatabase.getInstance(context);
    return db.putStoredFile(storedFile);
}