首页 文章 精选 留言 我的

精选列表

搜索[多媒体处理工具],共10000篇文章
优秀的个人博客,低调大师

SmartCall 自定义扩展实战:手把手实现专属拦截器与工具处理器

SmartCall 的技能编排引擎提供了配置化的通用能力:通过页面配置即可实现关键词转人工、定时提醒、HTTP 接口调用等常见逻辑,覆盖了 80% 的标准业务场景。 但在实际落地中,很多场景需要更深的定制:比如对话情绪识别、自研业务系统对接、专属质检规则、复杂状态机控制等,仅靠配置化技能无法满足。

优秀的个人博客,低调大师

Android笔记:bitmap转换与处理相关工具类,Bitmap与DrawAble与byte[]与InputStream之间的转换

1.将view转为bitmap 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // 将view转为bitmap public static Bitmap getBitmapFromView(View view) { // Define a bitmap with the same size as the view Bitmap returnedBitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(), Bitmap.Config.ARGB_8888); // Bind a canvas to it Canvas canvas = new Canvas(returnedBitmap); // Get the view's background Drawable bgDrawable = view.getBackground(); if (bgDrawable != null ) // has background drawable, then draw it on the canvas bgDrawable.draw(canvas); else // does not have background drawable, then draw white background on // the canvas canvas.drawColor(Color.WHITE); // draw the view on the canvas view.draw(canvas); // return the bitmap return returnedBitmap; } 2.将view转为bitmap 1 2 3 4 5 6 7 8 // 将view转为bitmap public static Bitmap viewToBitmap(View view) { view.setDrawingCacheEnabled( true ); view.buildDrawingCache(); Bitmap bm = view.getDrawingCache(); return bm; } 3.将xml转为bitmap 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 // 将xml转为bitmap public static Bitmap convertBitmapFromXML(Context context, String clusterSize, Bitmap bm) { View layout = LayoutInflater.from(context).inflate(R.layout.estatecartlist_item, null ); View bitmapView = layout.findViewById(R.id.estatecartlist_item_bitmap); TextView xml_text = (TextView) layout.findViewById(R.id.item_estatecart_tv_name); ImageView image = (ImageView) layout.findViewById(R.id.item_estatecart_iv_main); image.setImageBitmap(bm); xml_text.setText(clusterSize); bitmapView.measure(MeasureSpec.makeMeasureSpec( 0 , MeasureSpec.UNSPECIFIED), MeasureSpec.makeMeasureSpec( 0 , MeasureSpec.UNSPECIFIED)); bitmapView.layout( 0 , 0 , bitmapView.getMeasuredWidth(), bitmapView.getMeasuredHeight()); final Bitmap clusterBitmap = Bitmap.createBitmap(bitmapView.getMeasuredWidth(), bitmapView.getMeasuredHeight(), Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(clusterBitmap); bitmapView.draw(canvas); return clusterBitmap; } ==============参考资料=================== * 1.http://stackoverflow.com/questions/7200535/how-to-convert-views-to-bitmap * 2.http://stackoverflow.com/questions/5536066/convert-view-to-bitmap-on-android/9595919#9595919 * 3.http://stackoverflow.com/questions/12402392/android-converting-xml-view-to-bitmap-without-showing-it 4.图片缩放与压缩 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 // 按大小缩放 private Bitmap getimage(String srcPath) { BitmapFactory.Options newOpts = new BitmapFactory.Options(); // 开始读入图片,此时把options.inJustDecodeBounds 设回true了 newOpts.inJustDecodeBounds = true ; Bitmap bitmap = BitmapFactory.decodeFile(srcPath, newOpts); // 此时返回bm为空 newOpts.inJustDecodeBounds = false ; int w = newOpts.outWidth; int h = newOpts.outHeight; // 现在主流手机比较多是800*480分辨率,所以高和宽我们设置为 float hh = 800f; // 这里设置高度为800f float ww = 480f; // 这里设置宽度为480f // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可 int be = 1 ; // be=1表示不缩放 if (w > h && w > ww) { // 如果宽度大的话根据宽度固定大小缩放 be = ( int ) (newOpts.outWidth / ww); } else if (w < h && h > hh) { // 如果高度高的话根据宽度固定大小缩放 be = ( int ) (newOpts.outHeight / hh); } if (be <= 0 ) be = 1 ; newOpts.inSampleSize = be; // 设置缩放比例 // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了 bitmap = BitmapFactory.decodeFile(srcPath, newOpts); return compressImage(bitmap); // 压缩好比例大小后再进行质量压缩 } // 图片质量压缩 private static Bitmap compressImage(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100 , baos); // 质量压缩方法,这里100表示不压缩,把压缩后的数据存放到baos中 int options = 100 ; while (baos.toByteArray().length / 1024 > 100 ) { // 循环判断如果压缩后图片是否大于100kb,大于继续压缩 baos.reset(); // 重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG, options, baos); // 这里压缩options%,把压缩后的数据存放到baos中 options -= 10 ; // 每次都减少10 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray()); // 把压缩后的数据baos存放到ByteArrayInputStream中 Bitmap bitmap = BitmapFactory.decodeStream(isBm, null , null ); // 把ByteArrayInputStream数据生成图片 return bitmap; } // 图片按比例大小压缩 private static Bitmap comp(Bitmap image) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); image.compress(Bitmap.CompressFormat.JPEG, 100 , baos); if (baos.toByteArray().length / 1024 > 1024 ) { // 判断如果图片大于1M,进行压缩避免在生成图片(BitmapFactory.decodeStream)时溢出 baos.reset(); // 重置baos即清空baos image.compress(Bitmap.CompressFormat.JPEG, 50 , baos); // 这里压缩50%,把压缩后的数据存放到baos中 } ByteArrayInputStream isBm = new ByteArrayInputStream(baos.toByteArray()); BitmapFactory.Options newOpts = new BitmapFactory.Options(); // 开始读入图片,此时把options.inJustDecodeBounds 设回true了 newOpts.inJustDecodeBounds = true ; Bitmap bitmap = BitmapFactory.decodeStream(isBm, null , newOpts); newOpts.inJustDecodeBounds = false ; int w = newOpts.outWidth; int h = newOpts.outHeight; // 现在主流手机比较多是800*480分辨率,所以高和宽我们设置为 float hh = 800f; // 这里设置高度为800f float ww = 480f; // 这里设置宽度为480f // 缩放比。由于是固定比例缩放,只用高或者宽其中一个数据进行计算即可 int be = 1 ; // be=1表示不缩放 if (w > h && w > ww) { // 如果宽度大的话根据宽度固定大小缩放 be = ( int ) (newOpts.outWidth / ww); } else if (w < h && h > hh) { // 如果高度高的话根据宽度固定大小缩放 be = ( int ) (newOpts.outHeight / hh); } if (be <= 0 ) be = 1 ; newOpts.inSampleSize = be; // 设置缩放比例 // 重新读入图片,注意此时已经把options.inJustDecodeBounds 设回false了 isBm = new ByteArrayInputStream(baos.toByteArray()); bitmap = BitmapFactory.decodeStream(isBm, null , newOpts); return compressImage(bitmap); // 压缩好比例大小后再进行质量压缩 } 5.图片转为文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 // 图片转为文件 public static boolean saveBitmap2file(Bitmap bmp, String filename) { CompressFormat format = Bitmap.CompressFormat.JPEG; int quality = 100 ; OutputStream stream = null ; try { stream = new FileOutputStream( "/sdcard/" + filename); } catch (FileNotFoundException e) { e.printStackTrace(); } return bmp.compress(format, quality, stream); } 6.屏幕截屏方法 1 2 3 4 5 6 7 8 9 // 屏幕截屏方法 获取当前屏幕bitmap,转换成bytes[] 调用 UI分享方法 public void printscreen_share(View v) { View view1 = getWindow().getDecorView(); Display display = getWindowManager().getDefaultDisplay(); view1.layout( 0 , 0 , display.getWidth(), display.getHeight()); view1.setDrawingCacheEnabled( true ); Bitmap bitmap = Bitmap.createBitmap(view1.getDrawingCache()); } 7.把Bitmap 转成 Byte 1 2 3 4 5 6 7 // 把Bitmap 转成 Byte public static byte [] Bitmap2Bytes(Bitmap bm) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, 100 , baos); return baos.toByteArray(); } 8.图片转为文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 // 图片转为文件 public static boolean saveBitmap2file(Bitmap bmp) { CompressFormat format = Bitmap.CompressFormat.PNG; int quality = 100 ; OutputStream stream = null ; try { // 判断SDcard状态 if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { // 错误提示 return false ; } // 检查SDcard空间 File SDCardRoot = Environment.getExternalStorageDirectory(); if (SDCardRoot.getFreeSpace() < 10000 ) { // 弹出对话框提示用户空间不够 Log.e( "Utils" , "存储空间不够" ); return false ; } // 在SDcard创建文件夹及文件 File bitmapFile = new File(SDCardRoot.getPath() + FILE_PATH); bitmapFile.getParentFile().mkdirs(); // 创建文件夹 stream = new FileOutputStream(SDCardRoot.getPath() + FILE_PATH); // "/sdcard/" } catch (FileNotFoundException e) { e.printStackTrace(); } return bmp.compress(format, quality, stream); } 9.下载图片 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 // 下载图片 public static Bitmap loadImage(String... params) { InputStream is = null ; Bitmap bitmap = null ; try { URL url = new URL(params[ 0 ]); HttpURLConnection conn = (HttpURLConnection) url.openConnection(); conn.setReadTimeout( 5000 ); conn.setConnectTimeout( 5000 ); if (HttpURLConnection.HTTP_OK != conn.getResponseCode()) { // 网络连接异常 Log.e( "" , "loadImage连接异常" ); return null ; } is = conn.getInputStream(); bitmap = BitmapFactory.decodeStream(is); } catch (MalformedURLException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } finally { if ( null != is) { try { is.close(); } catch (IOException e) { e.printStackTrace(); } } } return bitmap; } 10.byte[]转换成Bitmap 1 2 3 4 5 6 7 8 9 // byte[]转换成Bitmap public static Bitmap Bytes2Bitmap( byte [] b) { if (b.length != 0 ) { return BitmapFactory.decodeByteArray(b, 0 , b.length); } return null ; } 11.将字符串转换成Bitmap类型 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 public static Bitmap stringtoBitmap(String string) { // 将字符串转换成Bitmap类型 Bitmap bitmap = null ; try { byte [] bitmapArray; bitmapArray = Base64.decode(string, Base64.DEFAULT); bitmap = BitmapFactory.decodeByteArray(bitmapArray, 0 , bitmapArray.length); } catch (Exception e) { e.printStackTrace(); } return bitmap; } 12.将Bitmap转换成字符串 1 2 3 4 5 6 7 8 9 10 public static String bitmaptoString(Bitmap bitmap) { // 将Bitmap转换成字符串 String string = null ; ByteArrayOutputStream bStream = new ByteArrayOutputStream(); bitmap.compress(CompressFormat.PNG, 100 , bStream); byte [] bytes = bStream.toByteArray(); string = Base64.encodeToString(bytes, Base64.DEFAULT); return string; } 13.byte[]转为文件 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 //byte[]转为文件 public static File getFileFromBytes( byte [] b) { BufferedOutputStream stream = null ; File file = null ; try { // 判断SDcard状态 if (!Environment.MEDIA_MOUNTED.equals(Environment.getExternalStorageState())) { // 错误提示 return null ; } // 检查SDcard空间 File SDCardRoot = Environment.getExternalStorageDirectory(); if (SDCardRoot.getFreeSpace() < 10000 ) { // 弹出对话框提示用户空间不够 Log.e( "Utils" , "存储空间不够" ); return null ; } // 在SDcard创建文件夹及文件 File bitmapFile = new File(SDCardRoot.getPath() + FILE_PATH); bitmapFile.getParentFile().mkdirs(); // 创建文件夹 FileOutputStream fstream = new FileOutputStream(bitmapFile); stream = new BufferedOutputStream(fstream); stream.write(b); } catch (Exception e) { e.printStackTrace(); } finally { if (stream != null ) { try { stream.close(); } catch (IOException e1) { e1.printStackTrace(); } } } return file; } 14.图片压缩 1 2 3 4 5 6 7 8 9 10 11 12 13 //图片缩放 public static Bitmap scaleDownBitmap(Bitmap photo, int newHeight, Context context) { final float densityMultiplier = context.getResources().getDisplayMetrics().density; int h = ( int ) (newHeight * densityMultiplier); int w = ( int ) (h * photo.getWidth() / (( double ) photo.getHeight())); photo = Bitmap.createScaledBitmap(photo, w, h, true ); return photo; } 15.将byte[]转换成InputStream 1 2 3 4 5 6 // 将byte[]转换成InputStream public InputStream Byte2InputStream( byte [] b) { ByteArrayInputStream bais = new ByteArrayInputStream(b); return bais; } 16.将InputStream转换成byte[] 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 // 将InputStream转换成byte[] public byte [] InputStream2Bytes(InputStream is) { String str = "" ; byte [] readByte = new byte [ 1024 ]; int readCount = - 1 ; try { while ((readCount = is.read(readByte, 0 , 1024 )) != - 1 ) { str += new String(readByte).trim(); } return str.getBytes(); } catch (Exception e) { e.printStackTrace(); } return null ; } 17.将Bitmap转换成InputStream 1 2 3 4 5 6 7 8 // 将Bitmap转换成InputStream public InputStream Bitmap2InputStream(Bitmap bm) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.JPEG, 100 , baos); InputStream is = new ByteArrayInputStream(baos.toByteArray()); return is; } 18.将Bitmap转换成InputStream 1 2 3 4 5 6 7 8 // 将Bitmap转换成InputStream public InputStream Bitmap2InputStream(Bitmap bm, int quality) { ByteArrayOutputStream baos = new ByteArrayOutputStream(); bm.compress(Bitmap.CompressFormat.PNG, quality, baos); InputStream is = new ByteArrayInputStream(baos.toByteArray()); return is; } 19.将InputStream转换成Bitmap 1 2 3 4 5 // 将InputStream转换成Bitmap public Bitmap InputStream2Bitmap(InputStream is) { return BitmapFactory.decodeStream(is); } 20.Drawable转换成InputStream 1 2 3 4 5 6 // Drawable转换成InputStream public InputStream Drawable2InputStream(Drawable d) { Bitmap bitmap = this .drawable2Bitmap(d); return this .Bitmap2InputStream(bitmap); } 21.InputStream转换成Drawable 1 2 3 4 5 6 // InputStream转换成Drawable public Drawable InputStream2Drawable(InputStream is) { Bitmap bitmap = this .InputStream2Bitmap(is); return this .bitmap2Drawable(bitmap); } 22.Drawable转换成byte[] 1 2 3 4 5 6 // Drawable转换成byte[] public byte [] Drawable2Bytes(Drawable d) { Bitmap bitmap = this .drawable2Bitmap(d); return this .Bitmap2Bytes(bitmap); } 23.byte[]转换成Drawable 1 2 3 4 5 6 // byte[]转换成Drawable public Drawable Bytes2Drawable( byte [] b) { Bitmap bitmap = this .Bytes2Bitmap(b); return this .bitmap2Drawable(bitmap); } 24.Drawable转换成Bitmap 1 2 3 4 5 6 7 8 9 10 // Drawable转换成Bitmap public Bitmap drawable2Bitmap(Drawable drawable) { Bitmap bitmap = Bitmap.createBitmap(drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight(), drawable.getOpacity() != PixelFormat.OPAQUE ? Bitmap.Config.ARGB_8888 : Bitmap.Config.RGB_565); Canvas canvas = new Canvas(bitmap); drawable.setBounds( 0 , 0 , drawable.getIntrinsicWidth(), drawable.getIntrinsicHeight()); drawable.draw(canvas); return bitmap; } 25.Bitmap转换成Drawable 1 2 3 4 5 6 7 // Bitmap转换成Drawable public Drawable bitmap2Drawable(Bitmap bitmap) { BitmapDrawable bd = new BitmapDrawable(bitmap); Drawable d = (Drawable) bd; return d; } 本文转自 glblong 51CTO博客,原文链接:http://blog.51cto.com/glblong/1304090,如需转载请自行联系原作者

优秀的个人博客,低调大师

python 文件处理

模式: 读'r' 写[清空整个文件]'w' 追加[文件需要存在]'a' 读写'r+' 二进制文件'b' 'rb','wb','rb+' 写文件 i={'ddd':'ccc'} f = file('poem.txt', 'a') f.write("string") f.write(str(i)) f.flush() f.close() 读文件 f = file('/etc/passwd','r') c = f.read().strip() # 读取为一个大字符串,并去掉最后一个换行符 for i in c.spilt('\n'): # 用换行符切割字符串得到列表循环每行 print i f.close() 读文件2 > for i in open('b.txt'): # 直接读取也可迭代,并有利于大文件读取,但不可反复读取 print i, 追加日志 > log = open('/home/peterli/xuesong','a') print >> log,'faaa' log.close() with读文件 with open('a.txt') as f: for i in f: print i print f.read() # 打印所有内容为字符串 print f.readlines() 文件随机读写 # 文件本没有换行,一切都是字符,文件也没有插入功能 f.tell() # 当前读写位置 f.read(5) # 读取5个字符并改变指针 f.seek(5) # 改变用户态读写指针偏移位置,可做随机写 f.seek(p,0) # 移动当文件第p个字节处,绝对位置 f.seek(p,1) # 移动到相对于当前位置之后的p个字节 f.seek(p,2) # 移动到相对文件尾之后的p个字节 f.seek(0,2) # 指针指到尾部 # 改变指针超出文件尾部,会造成文件洞,ll看占用较大,但du -sh却非常小 f.read(65535) # 读取64K字节 f.write("str") # 写会覆盖当前指针后的响应字符,无插入功能

优秀的个人博客,低调大师

Spring 表单处理

1. SimpleFormController vs @Controller In XML-based Spring MVC web application, you create a form controller by extending theSimpleFormControllerclass. In annotation-based, you can use@Controllerinstead. SimpleFormController public class CustomerController extends SimpleFormController{ //... } Annotation @Controller @RequestMapping("/customer.htm") public class CustomerController{ //... } 2. formBackingObject() vs RequestMethod.GET In SimpleFormController, you can initialize the command object for binding in theformBackingObject()method. In annotation-based, you can do the same by annotated the method name with@RequestMapping(method = RequestMethod.GET). SimpleFormController @Override protected Object formBackingObject(HttpServletRequest request) throws Exception { Customer cust = new Customer(); //Make "Spring MVC" as default checked value cust.setFavFramework(new String []{"Spring MVC"}); return cust; } Annotation @RequestMapping(method = RequestMethod.GET) public String initForm(ModelMap model){ Customer cust = new Customer(); //Make "Spring MVC" as default checked value cust.setFavFramework(new String []{"Spring MVC"}); //command object model.addAttribute("customer", cust); //return form view return "CustomerForm"; } 3. onSubmit() vs RequestMethod.POST In SimpleFormController, the form submission is handle by theonSubmit()method. In annotation-based, you can do the same by annotated the method name with@RequestMapping(method = RequestMethod.POST). SimpleFormController @Override protected ModelAndView onSubmit(HttpServletRequest request, HttpServletResponse response, Object command, BindException errors) throws Exception { Customer customer = (Customer)command; return new ModelAndView("CustomerSuccess"); } Annotation @RequestMapping(method = RequestMethod.POST) public String processSubmit( @ModelAttribute("customer") Customer customer, BindingResult result, SessionStatus status) { //clear the command object from the session status.setComplete(); //return form success view return "CustomerSuccess"; } 4. referenceData() vs @ModelAttribute In SimpleFormController, usually you put the reference data in model viareferenceData()method, so that the form view can access it. In annotation-based, you can do the same by annotated the method name with@ModelAttribute. SimpleFormController @Override protected Map referenceData(HttpServletRequest request) throws Exception { Map referenceData = new HashMap(); //Data referencing for web framework checkboxes List<String> webFrameworkList = new ArrayList<String>(); webFrameworkList.add("Spring MVC"); webFrameworkList.add("Struts 1"); webFrameworkList.add("Struts 2"); webFrameworkList.add("JSF"); webFrameworkList.add("Apache Wicket"); referenceData.put("webFrameworkList", webFrameworkList); return referenceData; } Spring’s form <form:checkboxes items="${webFrameworkList}" path="favFramework" /> Annotation @ModelAttribute("webFrameworkList") public List<String> populateWebFrameworkList() { //Data referencing for web framework checkboxes List<String> webFrameworkList = new ArrayList<String>(); webFrameworkList.add("Spring MVC"); webFrameworkList.add("Struts 1"); webFrameworkList.add("Struts 2"); webFrameworkList.add("JSF"); webFrameworkList.add("Apache Wicket"); return webFrameworkList; } Spring’s form <form:checkboxes items="${webFrameworkList}" path="favFramework" /> 5. initBinder() vs @InitBinder In SimpleFormController, you define the binding or register the custom property editor viainitBinder()method. In annotation-based, you can do the same by annotated the method name with@InitBinder. SimpleFormController protected void initBinder(HttpServletRequest request, ServletRequestDataBinder binder) throws Exception { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); } Annotation @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); } From Validation In SimpleFormController, you have to register and map the validator class to the controller class via XML bean configuration file, and the validation checking and work flows will be executed automatically. In annotation-based, you have to explicitly execute the validator and define the validation flow in the@Controllerclass manually. See the different : SimpleFormController <bean class="com.mkyong.customer.controller.CustomerController"> <property name="formView" value="CustomerForm" /> <property name="successView" value="CustomerSuccess" /> <!-- Map a validator --> <property name="validator"> <bean class="com.mkyong.customer.validator.CustomerValidator" /> </property> </bean> Annotation @Controller @RequestMapping("/customer.htm") public class CustomerController{ CustomerValidator customerValidator; @Autowired public CustomerController(CustomerValidator customerValidator){ this.customerValidator = customerValidator; } @RequestMapping(method = RequestMethod.POST) public String processSubmit( @ModelAttribute("customer") Customer customer, BindingResult result, SessionStatus status) { customerValidator.validate(customer, result); if (result.hasErrors()) { //if validator failed return "CustomerForm"; } else { status.setComplete(); //form success return "CustomerSuccess"; } } //... Full Example See a complete @Controller example. package com.mkyong.customer.controller; import java.sql.Date; import java.text.SimpleDateFormat; import java.util.ArrayList; import java.util.LinkedHashMap; import java.util.List; import java.util.Map; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.propertyeditors.CustomDateEditor; import org.springframework.stereotype.Controller; import org.springframework.ui.ModelMap; import org.springframework.validation.BindingResult; import org.springframework.web.bind.WebDataBinder; import org.springframework.web.bind.annotation.InitBinder; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.support.SessionStatus; import com.mkyong.customer.model.Customer; import com.mkyong.customer.validator.CustomerValidator; @Controller @RequestMapping("/customer.htm") public class CustomerController{ CustomerValidator customerValidator; @Autowired public CustomerController(CustomerValidator customerValidator){ this.customerValidator = customerValidator; } @RequestMapping(method = RequestMethod.POST) public String processSubmit( @ModelAttribute("customer") Customer customer, BindingResult result, SessionStatus status) { customerValidator.validate(customer, result); if (result.hasErrors()) { //if validator failed return "CustomerForm"; } else { status.setComplete(); //form success return "CustomerSuccess"; } } @RequestMapping(method = RequestMethod.GET) public String initForm(ModelMap model){ Customer cust = new Customer(); //Make "Spring MVC" as default checked value cust.setFavFramework(new String []{"Spring MVC"}); //Make "Make" as default radio button selected value cust.setSex("M"); //make "Hibernate" as the default java skills selection cust.setJavaSkills("Hibernate"); //initilize a hidden value cust.setSecretValue("I'm hidden value"); //command object model.addAttribute("customer", cust); //return form view return "CustomerForm"; } @ModelAttribute("webFrameworkList") public List<String> populateWebFrameworkList() { //Data referencing for web framework checkboxes List<String> webFrameworkList = new ArrayList<String>(); webFrameworkList.add("Spring MVC"); webFrameworkList.add("Struts 1"); webFrameworkList.add("Struts 2"); webFrameworkList.add("JSF"); webFrameworkList.add("Apache Wicket"); return webFrameworkList; } @InitBinder public void initBinder(WebDataBinder binder) { SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd"); binder.registerCustomEditor(Date.class, new CustomDateEditor(dateFormat, true)); } @ModelAttribute("numberList") public List<String> populateNumberList() { //Data referencing for number radiobuttons List<String> numberList = new ArrayList<String>(); numberList.add("Number 1"); numberList.add("Number 2"); numberList.add("Number 3"); numberList.add("Number 4"); numberList.add("Number 5"); return numberList; } @ModelAttribute("javaSkillsList") public Map<String,String> populateJavaSkillList() { //Data referencing for java skills list box Map<String,String> javaSkill = new LinkedHashMap<String,String>(); javaSkill.put("Hibernate", "Hibernate"); javaSkill.put("Spring", "Spring"); javaSkill.put("Apache Wicket", "Apache Wicket"); javaSkill.put("Struts", "Struts"); return javaSkill; } @ModelAttribute("countryList") public Map<String,String> populateCountryList() { //Data referencing for java skills list box Map<String,String> country = new LinkedHashMap<String,String>(); country.put("US", "United Stated"); country.put("CHINA", "China"); country.put("SG", "Singapore"); country.put("MY", "Malaysia"); return country; } } To make annotation work, you have to enable the component auto scanning feature in Spring. <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-2.5.xsd"> <context:component-scan base-package="com.mkyong.customer.controller" /> <bean class="com.mkyong.customer.validator.CustomerValidator" /> <!-- Register the Customer.properties --> <bean id="messageSource" class="org.springframework.context.support.ResourceBundleMessageSource"> <property name="basename" value="com/mkyong/customer/properties/Customer" /> </bean> <bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" > <property name="prefix"> <value>/WEB-INF/pages/</value> </property> <property name="suffix"> <value>.jsp</value> </property> </bean> </beans> Download Source Code Download it – SpringMVC-Form-Handling-Annotation-Example.zip(12KB) ============================================================================== 本文转自被遗忘的博客园博客,原文链接:http://www.cnblogs.com/rollenholt/archive/2012/12/27/2836249.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

android 图片处理

package com.android.image.demo;import java.io.InputStream;import android.app.Activity;import android.content.Context;import android.graphics.Bitmap;import android.graphics.BitmapFactory;import android.graphics.Canvas;import android.graphics.Color;import android.graphics.LinearGradient;import android.graphics.Paint;import android.graphics.Path;import android.graphics.PorterDuffXfermode;import android.graphics.Shader;import android.graphics.Typeface;import android.os.Bundle;import android.view.View;public class AlphaBitmap extends Activity { @Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState); setContentView(new SampleView(this)); }private static class SampleView extends View {private Bitmap mBitmap;private Bitmap mBitmap2;private Bitmap mBitmap3;private Shader mShader;private static void drawIntoBitmap(Bitmap bm) {float x = bm.getWidth();float y = bm.getHeight(); Canvas c = new Canvas(bm); Paint p = new Paint();/* Paint类的一个边缘光滑的方法,true表示边缘光滑*/ p.setAntiAlias(true); p.setAlpha(0x80);//设置颜色透明度为十六进制80(半透明),0x00全透明,0xFF不透明 /*在位图矩阵区域内画一个相切的圆*/ c.drawCircle(x/2, y/2, x/2, p); p.setAlpha(0x30);/*用指定的PorterDuff模型创建xformode,PorterDuff.Mode.SRC * 表示下面要绘制的文本应在上面绘制的圆的上层*/ p.setXfermode(new PorterDuffXfermode(android.graphics.PorterDuff.Mode.SRC)); p.setTextSize(60);/*Paint.Align 是文本对齐方式的一个枚举类 * CENTER表示文本居中 * LEFT 表示做对齐 * RIGHT 表示右对齐*/ p.setTextAlign(Paint.Align.CENTER);/*FontMetrics是字体度量的类描述了给定文本大小的各种各样的字体度量。 * ascent 表示到基准线之上的距离 * bottom 表示到基准线之下的最大距离,它是最低的字体类型 * descent 表示到基准线之下的距离 * leading 空格字符到基准线的距离,为0 * */ Paint.FontMetrics fm = p.getFontMetrics(); c.drawText("Alpha", x/2, (y-fm.ascent)/2, p); }public SampleView(Context context) {super(context); setFocusable(true);/*取得资源文件的输入流*/ InputStream is = context.getResources() .openRawResource(R.drawable.qq);/*BitmapFactory 是位图的一个工厂类 * 从各种各样的位图对象中创建位图对象,包括文件,流,字节数组。 * */ mBitmap = BitmapFactory.decodeStream(is);/*extractAlpha()位图的这个方法是通过提取 * 了原始位图的透明通道值重建新的位图*/ mBitmap2 = mBitmap.extractAlpha();/*通过位图的宽度和高度已经位图的颜色配置来创建位图 * Bitmap.Config是内部枚举类表示位图的颜色配置 * 它的颜色配置有ALPHA_8、ARGB_4444、ARGB_8888、RGB_565 * */ mBitmap3 = Bitmap.createBitmap(200, 200, Bitmap.Config.ALPHA_8); drawIntoBitmap(mBitmap3);/*LinearGradient类是Shader的一个子类,它实现的是一个线性梯度变化的一个 * 着色器,(0,0)到(100,70)的直线式颜色梯度变化线 * 这个梯度变化是在红绿蓝之间均匀变化的 * Shader.TileMode是超出梯度线的颜色变化模式 *CLAMP 固定shader绘画时颜色超过原始边界(梯度线)的部分颜色用边界颜色绘制。 *REPEAT 在水平和垂直方向重复使用着色器的色相,但边界分明 *MIRROR 在水平和垂直方向重复使用着色器的色相,交换的映像色相使得邻 *近的色相总是一致;颜色关于梯度线镜像 * */ mShader = new LinearGradient(0, 0, 100, 70,new int[] {Color.RED, Color.GREEN, Color.BLUE },null, Shader.TileMode.MIRROR); } @Override protected void onDraw(Canvas canvas) { canvas.drawColor(Color.WHITE); Paint p = new Paint();float y = 10;/*设置画笔颜色为红色*/ p.setColor(Color.RED);/*调用画布的drawBitmap方法在指定的位置用指定的画笔画指定的位图*/ canvas.drawBitmap(mBitmap, 10, y, p);/*设置下一个位图绘制的y坐标值*/ y += mBitmap.getHeight() + 10; canvas.drawBitmap(mBitmap2, 10, y, p); y += mBitmap2.getHeight() + 10;/*设置画笔的着色器*/ p.setShader(mShader); canvas.drawBitmap(mBitmap3, 10, y, p);/*这个类主要装载了绘制直线曲线等的几何路径。*/ Path path = new Path();/*画上面的梯度变化线*/ path.moveTo(0, 0); path.lineTo(100,70); p.setColor(Color.RED);/*Paint.Style画刷的样式枚举类 * STROKE 只绘制笔画形状 * Fill 填充 * FILL_AND_STROKE 既画笔画又填充 * */ p.setStyle(Paint.Style.STROKE);/*用指定的路径和指定的画刷画要求的路径*/ canvas.drawPath(path, p); } } } 本文转自wanqi博客园博客,原文链接http://www.cnblogs.com/wanqieddy/archive/2011/07/20/2111935.html:如需转载请自行联系原作者

优秀的个人博客,低调大师

iOS处理Orientation

在iOS6以后Orientation可以在plist文件里面进行设置。设置项是“Supported interface orientations”。 如果在iOS5或者一下版本UIViewController类默认支持Portrait only,要支持其他Orientation,需要重写shouldAutorotateToInterfaceOrientation:方法。 - (BOOL) shouldAutorotateToInterfaceOrientation: (UIInterfaceOrientation) orientation { return UIInterfaceOrientationIsPortrait(orientation); // only support portrait return YES; // support all orientations return (orientation != UIInterfaceOrientationPortraitUpsideDown); // anyting but } 本文转自Jake Lin博客园博客,原文链接:http://www.cnblogs.com/procoder/archive/2013/01/03/ios-orientations.html,如需转载请自行联系原作者

优秀的个人博客,低调大师

openstack 故障处理

系统磁盘损坏 前提:disk文件为文件存储类型的云主机。 步骤: 1、查看损坏OS云主机所在宿主机nova show 2、找到或创建一台与损坏云主机OS版本一致的云主机 3、将损坏云主机A的磁盘文件disk拷贝一份至用于修复云主机B disk_bak ls /var/lib/nova/instances/8a902cdf-2967-48c0-b928-df46544c78d5/disk_bak -rw-r--r-- 1 root root 36662149120 6月 25 15:29 disk_bak 4、在修云主机B目录下创建xml文件 相关target信息根据在宿主机查看的实例xml信息变更:virsh dumpxml instance-00021f44 1 2 3 4 5 6 cat attach.xml <disk type = 'file' device= 'disk' > <drivername= 'qemu' type = 'qcow2' cache= 'none' /> < source file = '/var/lib/nova/instances/8a902cdf-2967-48c0-b928-df46544c78d5/disk_bak' /> <targetdev= 'vdc' bus= 'virtio' /> < /disk > 5、加载磁盘 查看实例名称 Virsh list|grep8a902cdf-2967-48c0-b928-df46544c78d5 通过名称挂载disk virsh attach-device instance-00008ba9 attach.xml 成功附加设备 6、查看是否挂载成功 在宿主机上查看 virsh dumpxml instance-00008ba9 云主机内查看 fdisk -l 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 Disk /dev/vda :21.4GB,21474836480bytes 16heads,63sectors /track ,41610cylinders Units=cylindersof1008*512=516096bytes DeviceBootStartEndBlocksIdSystem /dev/vda1 *1407205127+83Linux /dev/vda2 408416102076631283Linux Disk /dev/vdb :1073MB,1073741824bytes 16heads,63sectors /track ,2080cylinders Units=cylindersof1008*512=516096bytes Disk /dev/vdb doesn'tcontainavalidpartitiontable Disk /dev/vdc :42.9GB,42949672960bytes 16heads,63sectors /track ,83220cylinders Units=cylindersof1008*512=516096bytes DeviceBootStartEndBlocksIdSystem /dev/vdc1 *1407205127+83Linux /dev/vdc2 408832204173775283Linux 7、操作完成后卸载 virsh detach-device instance-00008ba9 attach.xml 成功分离设备 忘记密码(rhel)、修复系统fsck 1、获取uuid nova list --all-tenants --ip ip_addr 2、获取url访问界面nova get-vnc-console uuid novnc 3、通过界面操作进入单用户模式,修改密码 I版nova stop uuid硬关机 在 icehouse 的版本中,执行 nova stop 时,会直接调用 virsh.destroy 硬关机 http://wiki.libvirt.org/page/FAQ#Why_doesn.27t_.27shutdown.27_seem_to_work.3F 修改源代码让其软关机超时后才执行硬关机解决 本文转自 qwjhq 51CTO博客,原文链接:http://blog.51cto.com/bingdian/1708910

优秀的个人博客,低调大师

openstack 异常处理

1, keystone 验证失败,例如:Authorization failed. The request you have made requires authentication. from 172.16.15.201 解决办法: keystone user-password-update --pass cinder cinder 2, 编辑/etc/cinder/api-paste.ini admin_tenant_name=services auth_host=172.16.15.201 service_port=5000 auth_port=35357 service_host=172.16.15.201 service_protocol=http admin_user=cinder auth_protocol=http admin_password=cinder#替换这一行 本文转自 swq499809608 51CTO博客,原文链接:http://blog.51cto.com/swq499809608/1342159

资源下载

更多资源
Nacos

Nacos

Nacos /nɑ:kəʊs/ 是 Dynamic Naming and Configuration Service 的首字母简称,一个易于构建 AI Agent 应用的动态服务发现、配置管理和AI智能体管理平台。Nacos 致力于帮助您发现、配置和管理微服务及AI智能体应用。Nacos 提供了一组简单易用的特性集,帮助您快速实现动态服务发现、服务配置、服务元数据、流量管理。Nacos 帮助您更敏捷和容易地构建、交付和管理微服务平台。

Spring

Spring

Spring框架(Spring Framework)是由Rod Johnson于2002年提出的开源Java企业级应用框架,旨在通过使用JavaBean替代传统EJB实现方式降低企业级编程开发的复杂性。该框架基于简单性、可测试性和松耦合性设计理念,提供核心容器、应用上下文、数据访问集成等模块,支持整合Hibernate、Struts等第三方框架,其适用范围不仅限于服务器端开发,绝大多数Java应用均可从中受益。

Sublime Text

Sublime Text

Sublime Text具有漂亮的用户界面和强大的功能,例如代码缩略图,Python的插件,代码段等。还可自定义键绑定,菜单和工具栏。Sublime Text 的主要功能包括:拼写检查,书签,完整的 Python API , Goto 功能,即时项目切换,多选择,多窗口等等。Sublime Text 是一个跨平台的编辑器,同时支持Windows、Linux、Mac OS X等操作系统。

WebStorm

WebStorm

WebStorm 是jetbrains公司旗下一款JavaScript 开发工具。目前已经被广大中国JS开发者誉为“Web前端开发神器”、“最强大的HTML5编辑器”、“最智能的JavaScript IDE”等。与IntelliJ IDEA同源,继承了IntelliJ IDEA强大的JS部分的功能。

用户登录
用户注册