`
xsuo
  • 浏览: 123380 次
  • 性别: Icon_minigender_1
  • 来自: 武汉
社区版块
存档分类
最新评论

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. }
分享到:
评论

相关推荐

    DATABASE_image.rar_DATABASE_image_SQL SAVE IMAGE PUDN_SQL 图片_sql

    本文将深入探讨如何在数据库中管理图像数据,主要基于标题和描述中的关键词,如"database_image"、"sql_save_image_pudn"、"sql_图片"、"sql__image"和"sql_image_读取"。 首先,我们来讨论如何在SQL数据库中存储...

    SaveImage_c#mysql数据库上传图片_more11h_MYSQL_savelmage_SAVe:IMAGe_

    标题"SaveImage_c#mysql数据库上传图片_more11h_MYSQL_savelmage_SAVe:IMAGe_"暗示我们将探讨一个C#应用程序,它能够将图像数据存储到MySQL数据库中。描述提到"连接mysql数据库,并且读取,保存图片的方法",意味着...

    C# 对SqlServer中Image字段的读写(例子)

    这可以通过`Image.Save`方法实现,提供一个`MemoryStream`,并指定适当的图像格式(如JPEG或PNG)。 - 创建`SqlCommand`,设置SQL插入语句,如:`INSERT INTO TableName (ImageField) VALUES (@ImageData)`。 - ...

    C#如何操作SQL中的Image类型数据

    image.Save(memoryStream, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] imageData = memoryStream.ToArray(); string query = "INSERT INTO TableName (ImageColumn) VALUES (@ImageData)"; SqlCommand ...

    Spectral Core Full Convert Enterprise v6.11.0.1683

    In-place image and BLOB viewing Selected rows deletion Jump to specific record Built-in table Print Preview and Print Table Customization Table customization available for each table separately ...

    picturebox中的Image转存到数据库

    image.Save(ms, image.RawFormat); byte[] imageData = ms.ToArray(); // 创建数据库连接 string connectionString = "Your Connection String"; using (SqlConnection connection = new SqlConnection...

    SQLiteExpertSetup

    Modify table structure visually without losing data already existing in the database. SQLite Expert will automatically create a new table with the new structure and copy the data from the old table. ...

    SQLiteExpertSetup.exe.part1

    1. Modify table structure visually without losing data already existing in the database. SQLite Expert will automatically create a new table with the new structure and copy the data from the old table...

    SQLiteExpertSetup.exe.part2

    1. Modify table structure visually without losing data already existing in the database. SQLite Expert will automatically create a new table with the new structure and copy the data from the old table...

    DIZipWriter v6.2.0 for D7-XE10.1 ZIP 压缩 解压缩

    // Save a TBitMap image to a ZIP archive. // Create and initialize a bitmap image. Img := TBitMap.Create; // Add a new entry to the ZIP archive. DIZipWriter.AddEntry('MyImage'); // Write the ...

    myBase Desktop V7.0.0 B22 专业版

    Added: support of cross-database hyperlinks, which allows to make hyperlinks to info items saved in different .nyf databases; It's required to first have target databases open before making cross-db ...

    C#_MySQL_图片的存储与读取

    pictureBox2.Image.Save(imageStream, System.Drawing.Imaging.ImageFormat.Jpeg); byte[] imageByte = imageStream.GetBuffer(); MySqlConnection conn = new MySqlConnection("Server=localhost;Uid=root;...

    RxLib控件包内含RxGIF,全部源码及DEMO

    save and restore columns order and display width in ini-files and system registry; display icons for BLOB, memo, OLE and picture fields; select multiple records; convert columns headings to buttons. ...

    如何加载图像以及保存图像到数据库中以及如何读取显示出来

    image.save("output.png", "PNG")) { // 处理保存失败的情况 } ``` 在保存图像到数据库之前,我们需要将图像转换为适合数据库存储的格式。通常,这涉及到将图像数据编码为字符串或二进制流。QT提供`QByteArray`类...

    基于ssm+mysql的在线订花系统源码数据库论文.docx

    MySQL, a popular open-source relational database management system, is utilized for storing and managing data related to flowers, orders, users, and other essential entities in the system. It ensures ...

    PLSQL.Developer(X32) v12.0.1.1814主程序+ v11中文包+keygen

    You can compare program units, tables, views, sequences with sources in the database, in a file or in a window. A new Oracle / Options preference "Always include owner prefix" has been added. When ...

    plsqldev12.0.4.1826x32主程序+ v12中文包+keygen

    You can compare program units, tables, views, sequences with sources in the database, in a file or in a window. A new Oracle / Options preference "Always include owner prefix" has been added. When ...

    PLSQL.Developer(X64) v12.0.1.1814 主程序+ v11中文包+keygen

    You can compare program units, tables, views, sequences with sources in the database, in a file or in a window. A new Oracle / Options preference "Always include owner prefix" has been added. When ...

    plsqldev12.0.4.1826x64主程序+ v12中文包+keygen

    You can compare program units, tables, views, sequences with sources in the database, in a file or in a window. A new Oracle / Options preference "Always include owner prefix" has been added. When ...

    Professional.MFC.with.VC6

    File Save and Save As File Open Print Font Browser Color Chooser Summary Chapter 6: User Interface Issues Developing Applications The Problems with Application Development The MFC Solution ...

Global site tag (gtag.js) - Google Analytics