save image in Database

handled this by saving the image to the ContentProvider
android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI and then
saving the created URI to the database along with my item. An example
of how to do this can be found here:

  1. /*
  2. *Copyright(C)2008GoogleInc.
  3. *
  4. *LicensedundertheApacheLicense,Version2.0(the"License");
  5. *youmaynotusethisfileexceptincompliancewiththeLicense.
  6. *YoumayobtainacopyoftheLicenseat
  7. *
  8. *http://www.apache.org/licenses/LICENSE-2.0
  9. *
  10. *Unlessrequiredbyapplicablelaworagreedtoinwriting,software
  11. *distributedundertheLicenseisdistributedonan"ASIS"BASIS,
  12. *WITHOUTWARRANTIESORCONDITIONSOFANYKIND,eitherexpressorimplied.
  13. *SeetheLicenseforthespecificlanguagegoverningpermissionsand
  14. *limitationsundertheLicense.
  15. */
  16. packagecom.google.android.photostream;
  17. importandroid.app.Activity;
  18. importandroid.content.Context;
  19. importandroid.content.Intent;
  20. importandroid.content.ActivityNotFoundException;
  21. importandroid.os.Bundle;
  22. importandroid.widget.TextView;
  23. importandroid.widget.ImageView;
  24. importandroid.widget.ViewAnimator;
  25. importandroid.widget.LinearLayout;
  26. importandroid.widget.Toast;
  27. importandroid.graphics.Bitmap;
  28. importandroid.graphics.BitmapFactory;
  29. importandroid.graphics.drawable.Drawable;
  30. importandroid.graphics.drawable.BitmapDrawable;
  31. importandroid.view.View;
  32. importandroid.view.ViewGroup;
  33. importandroid.view.ViewTreeObserver;
  34. importandroid.view.Menu;
  35. importandroid.view.MenuItem;
  36. importandroid.view.animation.AnimationUtils;
  37. importandroid.net.Uri;
  38. importjava.io.File;
  39. importjava.io.IOException;
  40. importjava.io.OutputStream;
  41. importjava.io.InputStream;
  42. importjava.io.FileNotFoundException;
  43. /**
  44. *Activitythatdisplaysaphotoalongwithitstitleandthedateatwhichitwastaken.
  45. *Thisactivityalsoletstheusersetthephotoasthewallpaper.
  46. */
  47. publicclassViewPhotoActivityextendsActivityimplementsView.OnClickListener,
  48. ViewTreeObserver.OnGlobalLayoutListener{
  49. staticfinalStringACTION="com.google.android.photostream.FLICKR_PHOTO";
  50. privatestaticfinalStringRADAR_ACTION="com.google.android.radar.SHOW_RADAR";
  51. privatestaticfinalStringRADAR_EXTRA_LATITUDE="latitude";
  52. privatestaticfinalStringRADAR_EXTRA_LONGITUDE="longitude";
  53. privatestaticfinalStringEXTRA_PHOTO="com.google.android.photostream.photo";
  54. privatestaticfinalStringWALLPAPER_FILE_NAME="wallpaper";
  55. privatestaticfinalintREQUEST_CROP_IMAGE=42;
  56. privateFlickr.PhotomPhoto;
  57. privateViewAnimatormSwitcher;
  58. privateImageViewmPhotoView;
  59. privateViewGroupmContainer;
  60. privateUserTask<?,?,?>mTask;
  61. privateTextViewmPhotoTitle;
  62. privateTextViewmPhotoDate;
  63. @Override
  64. protectedvoidonCreate(BundlesavedInstanceState){
  65. super.onCreate(savedInstanceState);
  66. mPhoto=getPhoto();
  67. setContentView(R.layout.screen_photo);
  68. setupViews();
  69. }
  70. /**
  71. *StartstheViewPhotoActivityforthespecifiedphoto.
  72. *
  73. *@paramcontextTheapplication'senvironment.
  74. *@paramphotoThephototodisplayandoptionallysetasawallpaper.
  75. */
  76. staticvoidshow(Contextcontext,Flickr.Photophoto){
  77. finalIntentintent=newIntent(context,ViewPhotoActivity.class);
  78. intent.putExtra(EXTRA_PHOTO,photo);
  79. context.startActivity(intent);
  80. }
  81. @Override
  82. protectedvoidonDestroy(){
  83. super.onDestroy();
  84. if(mTask!=null&&mTask.getStatus()!=UserTask.Status.RUNNING){
  85. mTask.cancel(true);
  86. }
  87. }
  88. privatevoidsetupViews(){
  89. mContainer=(ViewGroup)findViewById(R.id.container_photo);
  90. mSwitcher=(ViewAnimator)findViewById(R.id.switcher_menu);
  91. mPhotoView=(ImageView)findViewById(R.id.image_photo);
  92. mPhotoTitle=(TextView)findViewById(R.id.caption_title);
  93. mPhotoDate=(TextView)findViewById(R.id.caption_date);
  94. findViewById(R.id.menu_back).setOnClickListener(this);
  95. findViewById(R.id.menu_set).setOnClickListener(this);
  96. mPhotoTitle.setText(mPhoto.getTitle());
  97. mPhotoDate.setText(mPhoto.getDate());
  98. mContainer.setVisibility(View.INVISIBLE);
  99. //Setsupaviewtreeobserver.Thephotowillbescaledusingthesize
  100. //ofoneofourviewssowemustwaitforthefirstlayoutpasstobe
  101. //donetomakesurewehavethecorrectsize.
  102. mContainer.getViewTreeObserver().addOnGlobalLayoutListener(this);
  103. }
  104. /**
  105. *Loadsthephotoafterthefirstlayout.Thephotoisscaledusingthe
  106. *dimensionoftheImageViewthatwillultimatelycontainthephoto's
  107. *bitmap.WemakesurethattheImageViewislaidoutatleastonceto
  108. *getitscorrectsize.
  109. */
  110. publicvoidonGlobalLayout(){
  111. mContainer.getViewTreeObserver().removeGlobalOnLayoutListener(this);
  112. loadPhoto(mPhotoView.getMeasuredWidth(),mPhotoView.getMeasuredHeight());
  113. }
  114. /**
  115. *Loadsthephotoeitherfromthelastknowninstanceorfromthenetwork.
  116. *Loadingitfromthelastknowninstanceallowsforfastdisplayrotation
  117. *withouthavingtodownloadthephotofromthenetworkagain.
  118. *
  119. *@paramwidthThedesiredmaximumwidthofthephoto.
  120. *@paramheightThedesiredmaximumheightofthephoto.
  121. */
  122. privatevoidloadPhoto(intwidth,intheight){
  123. finalObjectdata=getLastNonConfigurationInstance();
  124. if(data==null){
  125. mTask=newLoadPhotoTask().execute(mPhoto,width,height);
  126. }else{
  127. mPhotoView.setImageBitmap((Bitmap)data);
  128. mSwitcher.showNext();
  129. }
  130. }
  131. /**
  132. *Loadsthe{@linkcom.google.android.photostream.Flickr.Photo}todisplay
  133. *fromtheintentusedtostarttheactivity.
  134. *
  135. *@returnThephototodisplay,ornullifthephotocannotbefound.
  136. */
  137. publicFlickr.PhotogetPhoto(){
  138. finalIntentintent=getIntent();
  139. finalBundleextras=intent.getExtras();
  140. Flickr.Photophoto=null;
  141. if(extras!=null){
  142. photo=extras.getParcelable(EXTRA_PHOTO);
  143. }
  144. returnphoto;
  145. }
  146. @Override
  147. publicbooleanonCreateOptionsMenu(Menumenu){
  148. getMenuInflater().inflate(R.menu.view_photo,menu);
  149. returnsuper.onCreateOptionsMenu(menu);
  150. }
  151. @Override
  152. publicbooleanonMenuItemSelected(intfeatureId,MenuItemitem){
  153. switch(item.getItemId()){
  154. caseR.id.menu_item_radar:
  155. onShowRadar();
  156. break;
  157. }
  158. returnsuper.onMenuItemSelected(featureId,item);
  159. }
  160. privatevoidonShowRadar(){
  161. newShowRadarTask().execute(mPhoto);
  162. }
  163. publicvoidonClick(Viewv){
  164. switch(v.getId()){
  165. caseR.id.menu_back:
  166. onBack();
  167. break;
  168. caseR.id.menu_set:
  169. onSet();
  170. break;
  171. }
  172. }
  173. privatevoidonSet(){
  174. mTask=newCropWallpaperTask().execute(mPhoto);
  175. }
  176. privatevoidonBack(){
  177. finish();
  178. }
  179. /**
  180. *Ifwesuccessfullyloadedaphoto,sendittoourfutureselftoallow
  181. *forfastdisplayrotation.Bydoingso,weavoidreloadingthephoto
  182. *fromthenetworkwhentheactivityistakendownandrecreatedupon
  183. *displayrotation.
  184. *
  185. *@returnTheBitmapdisplayedintheImageView,ornullifthephoto
  186. *wasn'tloaded.
  187. */
  188. @Override
  189. publicObjectonRetainNonConfigurationInstance(){
  190. finalDrawabled=mPhotoView.getDrawable();
  191. returnd!=null?((BitmapDrawable)d).getBitmap():null;
  192. }
  193. @Override
  194. protectedvoidonActivityResult(intrequestCode,intresultCode,Intentdata){
  195. //Spawnsanewtasktosetthewallpaperinabackgroundthreadwhen/if
  196. //wereceiveasuccessfulresultfromtheimagecropper.
  197. if(requestCode==REQUEST_CROP_IMAGE){
  198. if(resultCode==RESULT_OK){
  199. mTask=newSetWallpaperTask().execute();
  200. }else{
  201. cleanupWallpaper();
  202. showWallpaperError();
  203. }
  204. }
  205. }
  206. privatevoidshowWallpaperError(){
  207. Toast.makeText(ViewPhotoActivity.this,R.string.error_cannot_save_file,
  208. Toast.LENGTH_SHORT).show();
  209. }
  210. privatevoidshowWallpaperSuccess(){
  211. Toast.makeText(ViewPhotoActivity.this,R.string.success_wallpaper_set,
  212. Toast.LENGTH_SHORT).show();
  213. }
  214. privatevoidcleanupWallpaper(){
  215. deleteFile(WALLPAPER_FILE_NAME);
  216. mSwitcher.showNext();
  217. }
  218. /**
  219. *BackgroundtasktoloadthephotofromFlickr.Thetaskloadsthebitmap,
  220. *thenscaleittotheappropriatedimension.Thetaskendsbyreadjusting
  221. *theactivity'slayoutsothateverythingalignscorrectly.
  222. */
  223. privateclassLoadPhotoTaskextendsUserTask<Object,Void,Bitmap>{
  224. publicBitmapdoInBackground(Object...params){
  225. Bitmapbitmap=((Flickr.Photo)params[0]).loadPhotoBitmap(Flickr.PhotoSize.MEDIUM);
  226. if(bitmap==null){
  227. bitmap=BitmapFactory.decodeResource(getResources(),R.drawable.not_found);
  228. }
  229. finalintwidth=(Integer)params[1];
  230. finalintheight=(Integer)params[2];
  231. finalBitmapframed=ImageUtilities.scaleAndFrame(bitmap,width,height);
  232. bitmap.recycle();
  233. returnframed;
  234. }
  235. @Override
  236. publicvoidonPostExecute(Bitmapresult){
  237. mPhotoView.setImageBitmap(result);
  238. //Findbyhowmanypixelsthetitleanddatemustbeshiftedonthe
  239. //horizontalaxistobeleftalignedwiththephoto
  240. finalintoffsetX=(mPhotoView.getMeasuredWidth()-result.getWidth())/2;
  241. //ForcestheImageViewtohavethesamesizeasitsembeddedbitmap
  242. //Thiswillremovetheemptyspacebetweenthetitle/datepairand
  243. //thephotoitself
  244. LinearLayout.LayoutParamsparams;
  245. params=(LinearLayout.LayoutParams)mPhotoView.getLayoutParams();
  246. params.height=result.getHeight();
  247. params.weight=0.0f;
  248. mPhotoView.setLayoutParams(params);
  249. params=(LinearLayout.LayoutParams)mPhotoTitle.getLayoutParams();
  250. params.leftMargin=offsetX;
  251. mPhotoTitle.setLayoutParams(params);
  252. params=(LinearLayout.LayoutParams)mPhotoDate.getLayoutParams();
  253. params.leftMargin=offsetX;
  254. mPhotoDate.setLayoutParams(params);
  255. mSwitcher.showNext();
  256. mContainer.startAnimation(AnimationUtils.loadAnimation(ViewPhotoActivity.this,
  257. R.anim.fade_in));
  258. mContainer.setVisibility(View.VISIBLE);
  259. mTask=null;
  260. }
  261. }
  262. /**
  263. *Backgroundtasktocropalargeversionoftheimage.Thecroppedresultwill
  264. *besetasawallpaper.Thetaskssartsbyshowingtheprogressbar,then
  265. *downloadsthelargeversionofhthephotointoatemporaryfileandendsby
  266. *sendinganintenttotheCameraapplicationtocroptheimage.
  267. */
  268. privateclassCropWallpaperTaskextendsUserTask<Flickr.Photo,Void,Boolean>{
  269. privateFilemFile;
  270. @Override
  271. publicvoidonPreExecute(){
  272. mFile=getFileStreamPath(WALLPAPER_FILE_NAME);
  273. mSwitcher.showNext();
  274. }
  275. publicBooleandoInBackground(Flickr.Photo...params){
  276. booleansuccess=false;
  277. OutputStreamout=null;
  278. try{
  279. out=openFileOutput(mFile.getName(),MODE_WORLD_READABLE|MODE_WORLD_WRITEABLE);
  280. Flickr.get().downloadPhoto(params[0],Flickr.PhotoSize.LARGE,out);
  281. success=true;
  282. }catch(FileNotFoundExceptione){
  283. android.util.Log.e(Flickr.LOG_TAG,"Couldnotdownloadphoto",e);
  284. success=false;
  285. }catch(IOExceptione){
  286. android.util.Log.e(Flickr.LOG_TAG,"Couldnotdownloadphoto",e);
  287. success=false;
  288. }finally{
  289. if(out!=null){
  290. try{
  291. out.close();
  292. }catch(IOExceptione){
  293. success=false;
  294. }
  295. }
  296. }
  297. returnsuccess;
  298. }
  299. @Override
  300. publicvoidonPostExecute(Booleanresult){
  301. if(!result){
  302. cleanupWallpaper();
  303. showWallpaperError();
  304. }else{
  305. finalintwidth=getWallpaperDesiredMinimumWidth();
  306. finalintheight=getWallpaperDesiredMinimumHeight();
  307. finalIntentintent=newIntent("com.android.camera.action.CROP");
  308. intent.setClassName("com.android.camera","com.android.camera.CropImage");
  309. intent.setData(Uri.fromFile(mFile));
  310. intent.putExtra("outputX",width);
  311. intent.putExtra("outputY",height);
  312. intent.putExtra("aspectX",width);
  313. intent.putExtra("aspectY",height);
  314. intent.putExtra("scale",true);
  315. intent.putExtra("noFaceDetection",true);
  316. intent.putExtra("output",Uri.parse("file:/"+mFile.getAbsolutePath()));
  317. startActivityForResult(intent,REQUEST_CROP_IMAGE);
  318. }
  319. mTask=null;
  320. }
  321. }
  322. /**
  323. *Backgroundtasktosetthecroppedimageasthewallpaper.Thetasksimply
  324. *openthetemporaryfileandsetsitasthenewwallpaper.Thetaskendsby
  325. *deletingthetemporaryfileanddisplayamessagetotheuser.
  326. */
  327. privateclassSetWallpaperTaskextendsUserTask<Void,Void,Boolean>{
  328. publicBooleandoInBackground(Void...params){
  329. booleansuccess=false;
  330. InputStreamin=null;
  331. try{
  332. in=openFileInput(WALLPAPER_FILE_NAME);
  333. setWallpaper(in);
  334. success=true;
  335. }catch(IOExceptione){
  336. success=false;
  337. }finally{
  338. if(in!=null){
  339. try{
  340. in.close();
  341. }catch(IOExceptione){
  342. success=false;
  343. }
  344. }
  345. }
  346. returnsuccess;
  347. }
  348. @Override
  349. publicvoidonPostExecute(Booleanresult){
  350. cleanupWallpaper();
  351. if(!result){
  352. showWallpaperError();
  353. }else{
  354. showWallpaperSuccess();
  355. }
  356. mTask=null;
  357. }
  358. }
  359. privateclassShowRadarTaskextendsUserTask<Flickr.Photo,Void,Flickr.Location>{
  360. publicFlickr.LocationdoInBackground(Flickr.Photo...params){
  361. returnFlickr.get().getLocation(params[0]);
  362. }
  363. @Override
  364. publicvoidonPostExecute(Flickr.Locationlocation){
  365. if(location!=null){
  366. finalIntentintent=newIntent(RADAR_ACTION);
  367. intent.putExtra(RADAR_EXTRA_LATITUDE,location.getLatitude());
  368. intent.putExtra(RADAR_EXTRA_LONGITUDE,location.getLongitude());
  369. try{
  370. startActivity(intent);
  371. }catch(ActivityNotFoundExceptione){
  372. Toast.makeText(ViewPhotoActivity.this,R.string.error_cannot_find_radar,
  373. Toast.LENGTH_SHORT).show();
  374. }
  375. }else{
  376. Toast.makeText(ViewPhotoActivity.this,R.string.error_cannot_find_location,
  377. Toast.LENGTH_SHORT).show();
  378. }
  379. }
  380. }
  381. }

你可能感兴趣的:(apache,android,Google,OS)