List of usage examples for android.graphics BitmapFactory decodeFile
public static Bitmap decodeFile(String pathName)
From source file:fr.eoidb.util.ImageDownloader.java
private Bitmap loadSingleCacheFile(String url, Context context) { Bitmap bitmap = null;/*www. ja v a 2 s .c o m*/ File cacheIconFile = new File(context.getCacheDir(), getCacheFileName(url)); if (cacheIconFile.exists()) { if (BuildConfig.DEBUG) Log.v(LOG_TAG, "Loading cache file : " + url); bitmap = BitmapFactory.decodeFile(cacheIconFile.getAbsolutePath()); if (bitmap != null) { sHardBitmapCache.put(url, bitmap); } } return bitmap; }
From source file:es.uma.lcc.tasks.DecryptionRequestTask.java
public Void doInBackground(Void... parameters) { if (mPicId == null) { mDecodedBmp = BitmapFactory.decodeFile(mSrc); } else {// www . j av a 2 s .c o m DefaultHttpClient httpclient = new DefaultHttpClient(); final HttpParams params = new BasicHttpParams(); HttpClientParams.setRedirecting(params, false); httpclient.setParams(params); String target = SERVERURL + "?" + QUERYSTRING_ACTION + "=" + ACTION_READPERMISSIONS + "&" + QUERYSTRING_PICTUREID + "=" + mPicId; HttpGet httpget = new HttpGet(target); while (mCookie == null) // loop until authentication finishes, if necessary mCookie = mMainActivity.getCurrentCookie(); httpget.setHeader("Cookie", mCookie.getName() + "=" + mMainActivity.getCurrentCookie().getValue()); System.out.println("Cookie in header: " + mMainActivity.getCurrentCookie().getValue()); try { HttpResponse response = httpclient.execute(httpget); StatusLine status = response.getStatusLine(); if (status.getStatusCode() != 200) { mConnectionSucceeded = false; throw new IOException("Invalid response from server: " + status.toString()); } HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = entity.getContent(); ByteArrayOutputStream content = new ByteArrayOutputStream(); // Read response into a buffered stream int readBytes = 0; byte[] sBuffer = new byte[256]; while ((readBytes = inputStream.read(sBuffer)) != -1) { content.write(sBuffer, 0, readBytes); } String result = new String(content.toByteArray()); try { JSONArray jsonArray = new JSONArray(result); JSONObject jsonObj; if (jsonArray.length() == 0) { // should never happen Log.e(APP_TAG, LOG_ERROR + ": Malformed response from server"); } else { // Elements in a JSONArray keep their order JSONObject successState = jsonArray.getJSONObject(0); if (successState.get(JSON_RESULT).equals(JSON_RESULT_ERROR)) { if (successState.getBoolean(JSON_ISAUTHERROR) && mIsFirstRun) { mIsAuthError = true; Log.e(APP_TAG, LOG_ERROR + ": Server found an auth error: " + successState.get(JSON_REASON)); } else { Log.e(APP_TAG, LOG_ERROR + ": Server found an error: " + successState.get(JSON_REASON)); } } else { mSquareNum = jsonArray.length() - 1; mHorizStarts = new int[mSquareNum]; mHorizEnds = new int[mSquareNum]; mVertStarts = new int[mSquareNum]; mVertEnds = new int[mSquareNum]; mKeys = new String[mSquareNum]; for (int i = 0; i < mSquareNum; i++) { jsonObj = jsonArray.getJSONObject(i + 1); mHorizStarts[i] = jsonObj.getInt(JSON_HSTART); mHorizEnds[i] = jsonObj.getInt(JSON_HEND); mVertStarts[i] = jsonObj.getInt(JSON_VSTART); mVertEnds[i] = jsonObj.getInt(JSON_VEND); mKeys[i] = jsonObj.getString(JSON_KEY); } publishProgress(10); BitmapFactory.Options options = new BitmapFactory.Options(); options.inJustDecodeBounds = true; // get dimensions without reloading the image BitmapFactory.decodeFile(mSrc, options); mWidth = options.outWidth; mHeight = options.outHeight; mDecodedBmp = Bitmap.createBitmap(options.outWidth, options.outHeight, Config.ARGB_8888); if (mSquareNum == 0) { mDecodedBmp = BitmapFactory.decodeFile(mSrc); } else { mHasFoundKeys = true; byte[] pixels = MainActivity.decodeWrapperRegions(mSrc, mSquareNum, mHorizStarts, mHorizEnds, mVertStarts, mVertEnds, mKeys, mPicId); /* Native side returns each pixel as an RGBA quadruplet, with each a C unsigned byte ([0,255]). However, Java reads those as signed bytes ([-128, 127]) in two's complement. We mask them with 0xFF to ensure most significant bits set to 0, therefore interpreting them as their positive (unsigned) value. Furthermore, Java functions take pixels in ARGB (and not RGBA), so we manually re-order them */ int baseIndex; for (int i = 0; i < mWidth; i++) { for (int j = 0; j < mHeight; j++) { baseIndex = 4 * (j * mWidth + i); mDecodedBmp.setPixel(i, j, Color.argb(pixels[baseIndex + 3] & 0xff, pixels[baseIndex] & 0xff, pixels[baseIndex + 1] & 0xff, pixels[baseIndex + 2] & 0xff)); } } } } } } catch (JSONException jsonEx) { Log.e(APP_TAG, LOG_ERROR + ": Malformed JSON response from server"); mSquareNum = 0; } } } catch (ClientProtocolException e) { mConnectionSucceeded = false; Log.e(APP_TAG, LOG_ERROR + ": " + e.getMessage()); } catch (IOException e) { mConnectionSucceeded = false; Log.e(APP_TAG, LOG_ERROR + ": " + e.getMessage()); } } return null; }
From source file:com.nextgis.mobile.map.LocalTMSLayer.java
@Override public Bitmap getBitmap(TileItem tile) { //check if present TileCacheLevelDescItem item = mLimits.get(tile.getZoomLevel()); if (item != null && item.isInside(tile.getX(), tile.getY())) { File tilePath = new File(mPath, tile.toString("{z}/{x}/{y}.tile")); if (tilePath.exists()) return BitmapFactory.decodeFile(tilePath.getAbsolutePath()); }/*from www . j a va 2 s.c om*/ return null; }
From source file:or.tango.android.activity.PicActivity.java
@Override protected void findViews() { setTitle(""); setLeftVisible(true);//from ww w. ja v a 2 s. c o m setRightVisible(true); getRightBtn().setOnClickListener(this); picImageView = (ImageView) findViewById(R.id.pic_iv); progressView = (ProgressView) findViewById(R.id.progressView); picImageView.setImageBitmap(BitmapFactory.decodeFile(uploadFile.getAbsolutePath())); noMsgView = (View) findViewById(R.id.noMsgLayout); //handler=(ImageView)findViewById(R.id.handle); sd = (SlidingDrawer) findViewById(R.id.drawer); sd.setVisibility(View.INVISIBLE); resultLv = (ListView) findViewById(R.id.contentListView); adapter = new ArrayAdapter<String>(getApplicationContext(), R.layout.pic_adapter_item, R.id.item_text); resultLv.setAdapter(adapter); resultLv.setOnItemClickListener(new ItemClickListener()); Log.i(TAG, "FilePath:" + uploadFile.getAbsolutePath()); //?ip ?ip Config.HOST = MyPreferences.getHost(getApplicationContext()); }
From source file:com.surveyorexpert.TalkToMe.java
@Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.talk_main);/*from w w w .j a v a 2 s .c o m*/ SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this); String online = preferences.getString("ONLINE", ""); if (!online.equalsIgnoreCase("")) { ONLINE = online; } String PhotoPath = preferences.getString("PhotoPath", ""); if (!PhotoPath.equalsIgnoreCase("")) { mPhotoPath = PhotoPath; } String ServerPhotoPath = preferences.getString("ServerPhotoPath", ""); if (!ServerPhotoPath.equalsIgnoreCase("")) { mServerPhotoPath = ServerPhotoPath; } setTitle("mServerPhotoPath " + mServerPhotoPath); Bundle extras = getIntent().getExtras(); if (extras != null) { domain = extras.getString("domain"); project = extras.getString("project"); resource = extras.getString("resource"); nbcMarker = extras.getString("nbcMarker"); nbcDescription = extras.getString("nbcDescription"); userName = extras.getString("userName"); user_id = extras.getString("user_id"); severity = extras.getString("severity"); costEst = extras.getString("costEst"); version = extras.getString("version"); strLongitude = extras.getString("strLongitude"); strLatitude = extras.getString("strLatitude"); section = extras.getString("section"); element = extras.getString("element"); childPos = ""; //extras.getString("childPos"); parentPos = ""; //extras.getString("parentPos"); } // File imgFile = new File("/sdcard/Images/test_image.jpg"); // File imgFile = new File("/storage/emulated/0/1405349215602.jpg"); String path = Environment.getExternalStorageDirectory() + "/DCIM/Camera/1405349215602.jpg"; /* Toast.makeText(TalkToMe.this, "mServerPhotoPath = " + mServerPhotoPath , Toast.LENGTH_LONG).show(); */ /* Toast.makeText(getBaseContext(), "mPhotoPath = " + mPhotoPath, "mServerPhotoPath = " + mServerPhotoPath, Toast.LENGTH_LONG).show(); */ File imgFile = new File(mPhotoPath); if (imgFile.exists()) { Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath()); ImageView myImage = (ImageView) findViewById(R.id.finalImg); myImage.setImageBitmap(myBitmap); // Toast.makeText(getBaseContext(),"Set File " , Toast.LENGTH_LONG).show(); } else { Toast.makeText(getBaseContext(), "Not found " + imgFile.getName(), Toast.LENGTH_LONG).show(); } speak = (Button) findViewById(R.id.bt_speak); speak.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { sendRecognizeIntent(); } }); speak.setEnabled(false); confirm = (Button) findViewById(R.id.btWriteToServer); confirm.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { new PostComment().execute(); Toast.makeText(getBaseContext(), "TalkToMe Send to Server : " + "\nmPhotoPath : " + mPhotoPath + "\nsection : " + section + "\nelement : " + element + "\ngotMessage : " + gotMessage + "\ndomain : " + domain + "\nproject : " + project + "\nresource : " + resource + "\nnbcMarker : " + nbcMarker + "\nnbcDescription : " + nbcDescription + "\nuserName : " + userName + "\nuser_id : " + user_id + "\nseverity : " + severity + "\ncostEst : " + costEst + "\nversion : " + version + "\nstrLongitude : " + strLongitude + "\nstrLatitude : " + strLatitude, Toast.LENGTH_LONG).show(); } }); // confirm.setEnabled(false); result = (TextView) findViewById(R.id.tv_result); // message = (TextView)findViewById(R.id.tvTalkMessage); // message.setText(mServerPhotoPath); tts = new TextToSpeech(this, this); }
From source file:li.barter.fragments.EditProfileFragment.java
@Override public View onCreateView(final LayoutInflater inflater, final ViewGroup container, final Bundle savedInstanceState) { init(container, savedInstanceState); setHasOptionsMenu(true);//from w ww . j av a 2 s .c o m final View view = inflater.inflate(R.layout.fragment_profile_edit, null); setActionBarTitle(R.string.text_edit_profile); mAvatarBitmapTransformation = new AvatarBitmapTransformation(AvatarBitmapTransformation.AvatarSize.LARGE); mFirstNameTextView = (TextView) view.findViewById(R.id.text_first_name); mLastNameTextView = (TextView) view.findViewById(R.id.text_last_name); mAboutMeTextView = (TextView) view.findViewById(R.id.text_about_me); mPreferredLocationTextView = (TextView) view.findViewById(R.id.text_current_location); mProfileImageView = (RoundedCornerImageView) view.findViewById(R.id.image_profile_pic); mPreferredLocationTextView.setOnClickListener(this); mProfileImageView.setOnClickListener(this); mAvatarfile = new File(Environment.getExternalStorageDirectory(), mAvatarFileName); if (mAvatarfile.exists()) { final Bitmap bmp = BitmapFactory.decodeFile(mAvatarfile.getAbsolutePath()); mProfileImageView.setImageBitmap(bmp); } if (SharedPreferenceHelper.contains(R.string.pref_first_name)) { mFirstNameTextView.setText(SharedPreferenceHelper.getString(R.string.pref_first_name)); } else { mFirstNameTextView.setText(UserInfo.INSTANCE.getFirstName()); } if (SharedPreferenceHelper.contains(R.string.pref_last_name)) { mLastNameTextView.setText(SharedPreferenceHelper.getString(R.string.pref_last_name)); } if (SharedPreferenceHelper.contains(R.string.pref_description)) { mAboutMeTextView.setText(SharedPreferenceHelper.getString(R.string.pref_description)); } if (SharedPreferenceHelper.contains(R.string.pref_location)) { loadPreferredLocation(); } // for loading profile image String mProfileImageUrl = ""; if (SharedPreferenceHelper.contains(R.string.pref_profile_image)) { mProfileImageUrl = SharedPreferenceHelper.getString(R.string.pref_profile_image); } Picasso.with(getActivity()).load(mProfileImageUrl).transform(mAvatarBitmapTransformation) .error(R.drawable.pic_avatar).into(mProfileImageView.getTarget()); mCameraImageCaptureUri = Uri .fromFile(new File(android.os.Environment.getExternalStorageDirectory(), "barterli_avatar.jpg")); mChoosePictureDialogFragment = (SingleChoiceDialogFragment) getFragmentManager() .findFragmentByTag(FragmentTags.DIALOG_TAKE_PICTURE); return view; }
From source file:FacebookImageLoader.java
Bitmap downloadBitmap(final String url, File cacheFile) { // HttpClient works with older Android versions. final HttpClient client = new DefaultHttpClient(); final HttpGet getRequest = new HttpGet(url); try {//from ww w .java 2 s.com HttpResponse response = client.execute(getRequest); final int statusCode = response.getStatusLine().getStatusCode(); if (statusCode != HttpStatus.SC_OK) { Log.w(LOGCAT_NAME, "Error " + statusCode + " while retrieving bitmap from " + url); return null; } final HttpEntity entity = response.getEntity(); if (entity != null) { InputStream inputStream = null; try { inputStream = entity.getContent(); FlushedInputStream in = new FlushedInputStream(inputStream); if (cacheFile != null && cacheFile.exists()) { FileOutputStream fos = new FileOutputStream(cacheFile); while (true) { int bytedata = in.read(); if (bytedata == -1) break; fos.write(bytedata); } fos.close(); return BitmapFactory.decodeFile(cacheFile.getAbsolutePath()); } } finally { if (inputStream != null) { inputStream.close(); } entity.consumeContent(); } } } catch (IOException e) { getRequest.abort(); Log.w(LOGCAT_NAME, "I/O error while retrieving bitmap from " + url, e); } catch (IllegalStateException e) { getRequest.abort(); Log.w(LOGCAT_NAME, "Incorrect URL: " + url); } catch (Exception e) { getRequest.abort(); Log.w(LOGCAT_NAME, "Error while retrieving bitmap from " + url, e); } finally { } return null; }
From source file:com.phonegap.Capture.java
/** * Get the Image specific attributes/*from w ww . ja v a2s . c o m*/ * * @param filePath path to the file * @param obj represents the Media File Data * @return a JSONObject that represents the Media File Data * @throws JSONException */ private JSONObject getImageData(String filePath, JSONObject obj) throws JSONException { Bitmap bitmap = BitmapFactory.decodeFile(filePath); obj.put("height", bitmap.getHeight()); obj.put("width", bitmap.getWidth()); return obj; }
From source file:it.baywaylabs.jumpersumo.utility.FTPDownloadImage.java
/** * Background thread that download photo from the robot and prepare it for local processing or for Twitter reply.<br /> * This method is called when invoke <b>execute()</b>.<br /> * Do not invoke manually. Use: <i>new FTPDownloadImage().execute("");</i> * * @param params The parameters of the task. They can be <b>"local"</b> or <b>"twitter"</b>. * @return Null if everything was going ok. * @see #onPreExecute()//from w w w . j a va2s . c o m * @see #onPostExecute * @see #publishProgress */ @Override protected String doInBackground(String... params) { String resultFileName = ""; try { mFTPClient = new FTPClient(); // connecting to the host mFTPClient.connect(host, port); // Now check the reply code, if positive mean connection success if (FTPReply.isPositiveCompletion(mFTPClient.getReplyCode())) { // Login using username & password boolean status = mFTPClient.login(user, pass); mFTPClient.setFileType(FTP.BINARY_FILE_TYPE); mFTPClient.enterLocalPassiveMode(); mFTPClient.changeWorkingDirectory(Constants.DIR_ROBOT_MEDIA); FTPFile[] fileList = mFTPClient.listFiles(); long timestamp = 0l; String nameFile = ""; for (int i = 0; i < fileList.length; i++) { if (fileList[i].isFile() && fileList[i].getTimestamp().getTimeInMillis() > timestamp) { timestamp = fileList[i].getTimestamp().getTimeInMillis(); nameFile = fileList[i].getName(); } } Log.d(TAG, "File da scaricare: " + nameFile); mFTPClient.enterLocalActiveMode(); File folder = new File(Constants.DIR_ROBOT_IMG); OutputStream outputStream = null; boolean success = true; if (!folder.exists()) { success = folder.mkdir(); } if (params.length != 0 && !"".equals(nameFile)) if ("local".equals(params[0])) { try { outputStream = new FileOutputStream(folder.getAbsolutePath() + "/" + nameFile); success = mFTPClient.retrieveFile(nameFile, outputStream); } catch (Exception e) { return e.getMessage(); } finally { if (outputStream != null) { outputStream.close(); } } if (success) { resultFileName = nameFile; ContentResolver contentResolver = context.getContentResolver(); Bitmap bitmap = BitmapFactory.decodeFile(folder.getAbsolutePath() + "/" + nameFile); Log.e(TAG, "FileName: " + folder.getAbsolutePath() + "/" + nameFile); MediaStore.Images.Media.insertImage(contentResolver, bitmap, nameFile, "Jumper Sumo Photo"); mFTPClient.deleteFile(nameFile); File[] list = folder.listFiles(); for (int i = 0; i < list.length; i++) { if (nameFile.equals(list[i].getName())) list[i].delete(); } } } else if ("twitter".equals(params[0])) { try { outputStream = new FileOutputStream(folder.getAbsolutePath() + "/" + nameFile); success = mFTPClient.retrieveFile(nameFile, outputStream); } catch (Exception e) { return e.getMessage(); } finally { if (outputStream != null) { outputStream.close(); } } if (success) { resultFileName = nameFile; mFTPClient.deleteFile(nameFile); } } } } catch (Exception e) { return e.getMessage(); } finally { if (mFTPClient != null) { try { mFTPClient.logout(); mFTPClient.disconnect(); } catch (IOException e) { e.printStackTrace(); } } } if (!"".equals(resultFileName)) return resultFileName; return null; }
From source file:com.example.cuisoap.agrimac.homePage.machineDetail.machineInfoFragment.java
public void setupData() { if (machineDetailData.machine_paytype.equals("1")) { pay_type.check(R.id.machine_paytype1); } else {// www. j av a 2 s .c om pay_type.check(R.id.machine_paytype2); } machine_type.setText(machineDetailData.machine_type); if (machineDetailData.machine_powertype.equals("1")) { power_type.check(R.id.machine_powertype1); } else if (machineDetailData.machine_powertype.equals("2")) { power_type.check(R.id.machine_powertype2); } else if (machineDetailData.machine_powertype.equals("3")) { power_type.check(R.id.machine_powertype3); } else { power_type.check(R.id.machine_powertype4); } machine_name.setText(machineDetailData.machine_name); passenger_num.setText(machineDetailData.machine_maxpassenger); power.setText(machineDetailData.machine_power); wheel_distance.setText(machineDetailData.machine_wheeldistance); check_time.setText(machineDetailData.machine_checktime); String filename = img_path + machineDetailData.machine_license_filepath1.replace('/', '_'); File f = new File(filename); // File f=new File(machineDetailData.machine_license_filepath1); if (!f.exists()) { //TODO g new NormalLoadPictrue().getPicture(machineDetailData.machine_license_filepath1, license_pic1); } else { Bitmap b = BitmapFactory.decodeFile(filename); license_pic1.setImageBitmap(b); license_pic1.setVisibility(View.VISIBLE); } filename = img_path + machineDetailData.machine_license_filepath2.replace('/', '_'); f = new File(filename); if (!f.exists()) { new NormalLoadPictrue().getPicture(machineDetailData.machine_license_filepath2, license_pic2); } else { Bitmap b = BitmapFactory.decodeFile(filename); license_pic2.setImageBitmap(b); license_pic2.setVisibility(View.VISIBLE); } license1.setVisibility(View.GONE); license2.setVisibility(View.GONE); }