Example usage for android.graphics.drawable Drawable createFromStream

List of usage examples for android.graphics.drawable Drawable createFromStream

Introduction

In this page you can find the example usage for android.graphics.drawable Drawable createFromStream.

Prototype

public static Drawable createFromStream(InputStream is, String srcName) 

Source Link

Document

Create a drawable from an inputstream

Usage

From source file:com.scoreloop.android.coreui.BaseActivity.java

Drawable getDrawable(final String url) {
    if (!map.containsKey(url)) {
        final Drawable drawable = getResources().getDrawable(R.drawable.sl_game_default);
        map.put(url, drawable);/*  ww  w.  ja va2  s  .  c  o m*/

        final Thread thread = new Thread() {
            @Override
            public void run() {
                try {
                    final DefaultHttpClient httpClient = new DefaultHttpClient();
                    final HttpGet request = new HttpGet(url);
                    final HttpResponse response = httpClient.execute(request);
                    final InputStream inputStream = response.getEntity().getContent();
                    final Drawable drawable = Drawable.createFromStream(inputStream, "src");
                    map.put(url, drawable);
                } catch (final MalformedURLException e) {
                    map.remove(url);
                } catch (final IOException e) {
                    map.remove(url);
                }

                handler.post(notify);
            }
        };
        thread.start();
    }

    return map.get(url);
}

From source file:com.bnrc.util.AbFileUtil.java

/**
 * ??sset?./*from w w  w  .j a  v a2s  .c om*/
 *
 * @param context the context
 * @param fileName the file name
 * @return Drawable ?
 */
public static Drawable getDrawableFromAsset(Context context, String fileName) {
    Drawable drawable = null;
    try {
        AssetManager assetManager = context.getAssets();
        InputStream is = assetManager.open(fileName);
        drawable = Drawable.createFromStream(is, null);
    } catch (Exception e) {
        AbLogUtil.d(AbFileUtil.class, "?" + e.getMessage());
    }
    return drawable;
}

From source file:com.sogrey.sinaweibo.utils.FileUtil.java

/**
 * ???Asset?./*from   w  ww.  j a va2 s .c o m*/
 * 
 * @param context
 *            the context
 * @param fileName
 *            the file name
 * @return Drawable 
 */
public static Drawable getDrawableFromAsset(Context context, String fileName) {
    Drawable drawable = null;
    try {
        AssetManager assetManager = context.getAssets();
        InputStream is = assetManager.open(fileName);
        drawable = Drawable.createFromStream(is, null);
    } catch (Exception e) {
        LogUtil.d(FileUtil.class, "?" + e.getMessage());
    }
    return drawable;
}

From source file:com.c4mprod.utils.ImageDownloader.java

Bitmap downloadBitmap(String url) {
    // AndroidHttpClient is not allowed to be used from the main thread
    final HttpClient client = (mode == Mode.NO_ASYNC_TASK) ? new DefaultHttpClient()
            : AndroidHttpClient.newInstance("Android");
    final HttpGet getRequest = new HttpGet(url);

    try {/* w ww .jav  a  2  s .co  m*/

        // Log.i(Constants.PROJECT_TAG, "Downloading " + url);
        HttpResponse response = client.execute(getRequest);
        final int statusCode = response.getStatusLine().getStatusCode();
        if (statusCode != HttpStatus.SC_OK) {
            // Log.w(Constants.PROJECT_TAG, "Error " + statusCode + " while retrieving bitmap from " + url);
            return null;
        }

        final HttpEntity entity = response.getEntity();
        if (entity != null) {
            InputStream inputStream = null;
            try {
                inputStream = entity.getContent();

                // Log.d(Constants.PROJECT_TAG, "image url:" + urlString);
                Drawable drawable = Drawable.createFromStream(inputStream, "src");

                Bitmap bm = ((BitmapDrawable) drawable).getBitmap();

                // Log.d(Constants.PROJECT_TAG, "Bm width : " + bm.getWidth());

                // Log.d(Constants.PROJECT_TAG, "got a thumbnail drawable: " + drawable.getBounds() + ", " + drawable.getIntrinsicHeight() + ","
                // + drawable.getIntrinsicWidth() + ", " + drawable.getMinimumHeight() + "," + drawable.getMinimumWidth());
                if (mExternalStorageWriteable) {
                    File f = new File(mfolder, URLEncoder.encode(url));
                    // Log.d(Constants.PROJECT_TAG, f.getPath());
                    if (f.createNewFile()) {

                        OutputStream out = new FileOutputStream(f);

                        bm.compress(Bitmap.CompressFormat.JPEG, 80, out);
                        out.flush();
                        out.close();
                        // byte buf[]=new byte[1024];
                        // int len;
                        // while((len=is.read(buf))>0)
                        // out.write(buf,0,len);
                        out.close();

                    }
                }
                inputStream.close();
                return bm;

                // return BitmapFactory.decodeStream(inputStream);
                // Bug on slow connections, fixed in future release.
                // return BitmapFactory.decodeStream(new FlushedInputStream(inputStream));
            } finally {
                if (inputStream != null) {
                    inputStream.close();
                }
                entity.consumeContent();
            }
        }
    } catch (IOException e) {
        getRequest.abort();
        Log.w(LOG_TAG, "I/O error while retrieving bitmap from " + url, e);
    } catch (IllegalStateException e) {
        getRequest.abort();
        Log.w(LOG_TAG, "Incorrect URL: " + url);
    } catch (Exception e) {
        getRequest.abort();
        Log.w(LOG_TAG, "Error while retrieving bitmap from " + url, e);
    } finally {
        if ((client instanceof AndroidHttpClient)) {
            ((AndroidHttpClient) client).close();
        }
    }
    return null;
}

From source file:net.willwebberley.gowertides.ui.DayFragment.java

private void setWeatherInfo() {
    Weather weather = day.getWeather();/*w  w  w . j av a 2  s  .com*/
    String weather_description = weather.description;
    String unitType = prefs.getString("unitFormat", "true");
    Boolean metric = false;
    if (unitType.equals("true")) {
        metric = true;
    }

    int max_temp = weather.getMaxTemp(metric);
    int min_temp = weather.getMinTemp(metric);
    int wind_speed = weather.getWindSpeed(metric);
    Double prep = weather.precipitation;
    String direction = weather.wind_direction;
    Spanned temp = null, wind = null;
    if (metric) {
        temp = Html.fromHtml("<b>" + min_temp + "&deg;C - " + max_temp + "&deg;C</b>");
        wind = Html.fromHtml("<b>" + wind_speed + "km/h</b> from <b>" + direction + "</b>");

    } else {
        temp = Html.fromHtml("<b>" + min_temp + "&deg;F - " + max_temp + "&deg;F</b>");
        wind = Html.fromHtml("<b>" + wind_speed + "mph</b> from <b>" + direction + "</b>");
    }
    Spanned precipitation = Html.fromHtml("<b>" + prep + "mm</b>");

    ((TextView) layoutView.findViewById(R.id.weather_description)).setText(weather_description);
    ((TextView) layoutView.findViewById(R.id.weatherTemp)).setText(temp);
    ((TextView) layoutView.findViewById(R.id.weatherTemp)).setTextColor(Color.rgb(100, 100, 100));
    ((TextView) layoutView.findViewById(R.id.weatherWind)).setText(wind);
    ((TextView) layoutView.findViewById(R.id.weatherWind)).setTextColor(Color.rgb(100, 100, 100));
    ((TextView) layoutView.findViewById(R.id.weatherPrecipitation)).setText(precipitation);
    ((TextView) layoutView.findViewById(R.id.weatherPrecipitation)).setTextColor(Color.rgb(100, 100, 100));
    String icon = weather.getWeatherIcon();
    try {
        InputStream ims = getActivity().getAssets().open("icons/" + icon);
        Drawable d = Drawable.createFromStream(ims, null);
        ((ImageView) layoutView.findViewById(R.id.weatherIcon)).setImageDrawable(d);
        InputStream ims2 = getActivity().getAssets().open("icons/arrow.png");
        Drawable d2 = Drawable.createFromStream(ims2, null);
        ((ImageView) layoutView.findViewById(R.id.weatherWindIcon)).setImageDrawable(d2);

        RotateAnimation rAnim = new RotateAnimation(0, weather.wind_degree, Animation.RELATIVE_TO_SELF, 0.5f,
                Animation.RELATIVE_TO_SELF, 0.5f);
        rAnim.setDuration(500);
        rAnim.setFillEnabled(true);
        rAnim.setFillAfter(true);
        ((ImageView) layoutView.findViewById(R.id.weatherWindIcon)).startAnimation(rAnim);
    } catch (Exception e) {
        System.err.println(e);
    }
}

From source file:org.catnut.util.CatnutUtils.java

/**
 * ?//from   w ww  .  jav a 2s  .  c o m
 *
 * @param boundPx the icon' s rectangle bound, if zero, use the default
 */
public static SpannableString text2Emotion(Context context, String key, int boundPx) {
    SpannableString spannable = new SpannableString(key);
    InputStream inputStream = null;
    Drawable drawable = null;
    try {
        inputStream = context.getAssets().open(TweetImageSpan.EMOTIONS_DIR + TweetImageSpan.EMOTIONS.get(key));
        drawable = Drawable.createFromStream(inputStream, null);
    } catch (IOException e) {
        Log.e(TAG, "load emotion error!", e);
    } finally {
        closeIO(inputStream);
    }
    if (drawable != null) {
        if (boundPx == 0) {
            drawable.setBounds(0, 0, drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight());
        } else {
            drawable.setBounds(0, 0, boundPx, boundPx);
        }
        ImageSpan span = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
        spannable.setSpan(span, 0, key.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
    }
    return spannable;
}

From source file:com.danielme.muspyforandroid.services.MuspyClient.java

public Drawable getCover(String mbid) {
    Drawable drawable = null;//w w w  . jav  a  2  s .  c o m
    HttpURLConnection urlConnection = null;
    try {
        URL url = new URL(Constants.URL_COVER + mbid);
        urlConnection = (HttpURLConnection) url.openConnection();

        drawable = Drawable.createFromStream(urlConnection.getInputStream(), mbid);
    } catch (IOException ex1) {
        //cover not found
    } catch (Exception ex2) {
        Log.e(MuspyClient.class.toString(), ex2.getMessage(), ex2);
    } finally {
        urlConnection.disconnect();
    }

    return drawable;
}

From source file:com.facebook.samples.musicdashboard.MusicGalleryFragment.java

private Drawable fetchImageFromUrl(Context ctx, String url, String saveFilename) {
    try {// www . jav  a2  s  . co  m
        InputStream is = (InputStream) this.fetch(url);
        Drawable d = Drawable.createFromStream(is, "src");
        return d;
    } catch (MalformedURLException e) {
        Log.i(TAG, "Could not get fetch image.");
        return null;
    } catch (IOException e) {
        Log.i(TAG, "Could not get fetch image.");
        return null;
    }
}

From source file:com.metinkale.prayerapp.vakit.fragments.MainFragment.java

private void export(int csvpdf, LocalDate from, LocalDate to) throws IOException {
    File outputDir = getActivity().getCacheDir();
    if (!outputDir.exists())
        outputDir.mkdirs();//from w  w w  .  j  a  v a  2  s.  co  m
    File outputFile = new File(outputDir, mTimes.getName().replace(" ", "_") + (csvpdf == 0 ? ".csv" : ".pdf"));
    if (outputDir.exists())
        outputFile.delete();
    FileOutputStream outputStream;

    outputStream = new FileOutputStream(outputFile);
    if (csvpdf == 0) {
        outputStream.write("Date;Fajr;Shuruq;Dhuhr;Asr;Maghrib;Ishaa\n".getBytes());

        do {
            outputStream.write((from.toString("yyyy-MM-dd") + ";").getBytes());
            outputStream.write((mTimes.getTime(from, 0) + ";").getBytes());
            outputStream.write((mTimes.getTime(from, 1) + ";").getBytes());
            outputStream.write((mTimes.getTime(from, 2) + ";").getBytes());
            outputStream.write((mTimes.getTime(from, 3) + ";").getBytes());
            outputStream.write((mTimes.getTime(from, 4) + ";").getBytes());
            outputStream.write((mTimes.getTime(from, 5) + "\n").getBytes());
        } while (!(from = from.plusDays(1)).isAfter(to));
        outputStream.close();

    } else {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.KITKAT) {
            PdfDocument document = new PdfDocument();

            PdfDocument.PageInfo pageInfo = null;
            int pw = 595;
            int ph = 842;
            pageInfo = new PdfDocument.PageInfo.Builder(pw, ph, 1).create();
            PdfDocument.Page page = document.startPage(pageInfo);
            Drawable launcher = Drawable.createFromStream(getActivity().getAssets().open("pdf/launcher.png"),
                    null);
            Drawable qr = Drawable.createFromStream(getActivity().getAssets().open("pdf/qrcode.png"), null);
            Drawable badge = Drawable.createFromStream(
                    getActivity().getAssets().open("pdf/badge_" + Prefs.getLanguage() + ".png"), null);

            launcher.setBounds(30, 30, 30 + 65, 30 + 65);
            qr.setBounds(pw - 30 - 65, 30 + 65 + 5, pw - 30, 30 + 65 + 5 + 65);
            int w = 100;
            int h = w * badge.getIntrinsicHeight() / badge.getIntrinsicWidth();
            badge.setBounds(pw - 30 - w, 30 + (60 / 2 - h / 2), pw - 30, 30 + (60 / 2 - h / 2) + h);

            Canvas canvas = page.getCanvas();

            Paint paint = new Paint();
            paint.setARGB(255, 0, 0, 0);
            paint.setTextSize(10);
            paint.setTextAlign(Paint.Align.CENTER);
            canvas.drawText("com.metinkale.prayer", pw - 30 - w / 2, 30 + (60 / 2 - h / 2) + h + 10, paint);

            launcher.draw(canvas);
            qr.draw(canvas);
            badge.draw(canvas);

            paint.setARGB(255, 61, 184, 230);
            canvas.drawRect(30, 30 + 60, pw - 30, 30 + 60 + 5, paint);

            if (mTimes.getSource().resId != 0) {
                Drawable source = getResources().getDrawable(mTimes.getSource().resId);

                h = 65;
                w = h * source.getIntrinsicWidth() / source.getIntrinsicHeight();
                source.setBounds(30, 30 + 65 + 5, 30 + w, 30 + 65 + 5 + h);
                source.draw(canvas);
            }

            paint.setARGB(255, 0, 0, 0);
            paint.setTextSize(40);
            paint.setTextAlign(Paint.Align.LEFT);
            canvas.drawText(getText(R.string.appName).toString(), 30 + 65 + 5, 30 + 50, paint);
            paint.setTextAlign(Paint.Align.CENTER);
            paint.setFakeBoldText(true);
            canvas.drawText(mTimes.getName(), pw / 2.0f, 30 + 65 + 50, paint);

            paint.setTextSize(12);
            int y = 30 + 65 + 5 + 65 + 30;
            int p = 30;
            int cw = (pw - p - p) / 7;
            canvas.drawText(getString(R.string.date), 30 + (0.5f * cw), y, paint);
            canvas.drawText(Vakit.IMSAK.getString(), 30 + (1.5f * cw), y, paint);
            canvas.drawText(Vakit.GUNES.getString(), 30 + (2.5f * cw), y, paint);
            canvas.drawText(Vakit.OGLE.getString(), 30 + (3.5f * cw), y, paint);
            canvas.drawText(Vakit.IKINDI.getString(), 30 + (4.5f * cw), y, paint);
            canvas.drawText(Vakit.AKSAM.getString(), 30 + (5.5f * cw), y, paint);
            canvas.drawText(Vakit.YATSI.getString(), 30 + (6.5f * cw), y, paint);
            paint.setFakeBoldText(false);
            do {
                y += 20;
                canvas.drawText((from.toString("dd.MM.yyyy")), 30 + (0.5f * cw), y, paint);
                canvas.drawText((mTimes.getTime(from, 0)), 30 + (1.5f * cw), y, paint);
                canvas.drawText((mTimes.getTime(from, 1)), 30 + (2.5f * cw), y, paint);
                canvas.drawText((mTimes.getTime(from, 2)), 30 + (3.5f * cw), y, paint);
                canvas.drawText((mTimes.getTime(from, 3)), 30 + (4.5f * cw), y, paint);
                canvas.drawText((mTimes.getTime(from, 4)), 30 + (5.5f * cw), y, paint);
                canvas.drawText((mTimes.getTime(from, 5)), 30 + (6.5f * cw), y, paint);
            } while (!(from = from.plusDays(1)).isAfter(to));
            document.finishPage(page);

            document.writeTo(outputStream);

            // close the document
            document.close();

        } else {
            Toast.makeText(getActivity(), R.string.versionNotSupported, Toast.LENGTH_LONG).show();
        }
    }

    Intent shareIntent = new Intent();
    shareIntent.setAction(Intent.ACTION_SEND);
    shareIntent.setType(csvpdf == 0 ? "text/csv" : "application/pdf");

    Uri uri = FileProvider.getUriForFile(getActivity(), "com.metinkale.prayer.fileprovider", outputFile);
    shareIntent.putExtra(Intent.EXTRA_STREAM, uri);

    startActivity(Intent.createChooser(shareIntent, getResources().getText(R.string.export)));
}

From source file:com.adwhirl.AdWhirlManager.java

private Drawable fetchImage(String urlString) {
    try {//from  w  w w.ja  v a 2  s  . c  om
        URL url = new URL(urlString);
        InputStream is = (InputStream) url.getContent();
        Drawable d = Drawable.createFromStream(is, "src");
        return d;
    } catch (Exception e) {
        Log.e(AdWhirlUtil.ADWHIRL, "Unable to fetchImage(): ", e);
        return null;
    }
}